Skip to content

Instantly share code, notes, and snippets.

@btarg
Created September 8, 2024 18:23
Show Gist options
  • Save btarg/e07b428fe9bb86904574d8c192b4347e to your computer and use it in GitHub Desktop.
Save btarg/e07b428fe9bb86904574d8c192b4347e to your computer and use it in GitHub Desktop.
Godot 4 GDScript sort dictionaries
extends Node
var test_dict: Dictionary = {"world": 2, "hello": 1, "test" : 3}
func _ready():
var sorted := sort_dictionary_values(test_dict)
print(sorted) # {"hello" : 1, "world" : 2, "test" : 3}
class_name Util
## Swap elements in an array at indices i and j
static func swap(array: Array, i: int, j: int) -> void:
var temp = array[i]
array[i] = array[j]
array[j] = temp
## Sort an array based on another array's values
static func sort_arrays_by_values(values: Array, keys: Array, ascending: bool) -> void:
for i in range(values.size() - 1):
for j in range(i + 1, values.size()):
if (ascending and values[i] > values[j]) or (not ascending and values[i] < values[j]):
swap(values, i, j)
swap(keys, i, j)
## Sort a dictionary by values in ascending or descending order
static func sort_dictionary_values(dict: Dictionary, ascending: bool = false) -> Dictionary:
var values = dict.values()
var keys = dict.keys()
sort_arrays_by_values(values, keys, ascending)
var sorted_dict: Dictionary = {}
for i in range(values.size()):
sorted_dict[keys[i]] = values[i]
return sorted_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment