How to sort this array by value

{ “user43”: 434, “user1”: 123232233, “userD”: 99998, “test”: 1234, “user435”: 434545, “use8”: 99999 }

Arrays have a sort method but it doesn’t exist for dictionaries (that’s a dictionary).

try something like

# same dictionary
func sort_dict(dict: Dictionary) -> void:
    var pairs = dict.keys().map(func (key): return [key, dict[key]])
    pairs.sort()
    dict.clear()
    for p in pairs:
        dict[p[0]] = p[1]

# new dictionary
func sorted_dict(dict: Dictionary) -> Dictionary:
    var keys = dict.keys()
    keys.sort()
    var new_dict: = {}
    for k in keys:
        new_dict[k] = dict[k]
    return new_dict

edited: fixed first function

Your using a dictionary not an array.

Dictionaries are unsorted containers. This means they do not guarantee the order of their elements and are meant to be accessed by keys. This allows dictionaries to have certain optimisations which make them different from arrays, and give them different properties so that each arrays and dictionaries can be useful in different situations. While @cammymoop 's answer might work (I’ve not tried it), you shouldn’t rely on it because the implementation details for dictionaries could change and your code will break.

Instead, you might want to keep a separate array of keys and store them sorted. When you add or remove something from the dictionary do the same for your sorted array of keys. When you want to access the dictionary in a sorted order, iterate through the sorted array of keys. When you want to access a particular element in a non-sorted way, use the key directly with the dictionary.

An alternative, if you don’t need to access a single element very often, is to create a new class (RefCounted or Resource, as appropriate) which contains a key and value pair, then store an array of these objects. You can write a sort function to sort by the key of the pair. Or just keep two arrays (one of keys and one of values) and make sure you keep them in the same order (though this more prone to mistakes, I think).

Does that help?

Godot Dictionaries are ordered, they do guarantee the elements are in the order of insertion. So you can rely on the order of keys to be the same as the order of insertion.

1 Like

Just realized I forgot to actually do the sort in the first function though lol

func sort_dict(dict: Dictionary) -> void:
    var pairs = dict.keys().map(func (key): return [key, dict[key]])
    pairs.sort()
    dict.clear()
    for p in pairs:
        dict[p[0]] = p[1]

This compares the [key, value] arrays so the values do influence the sorting of keys that tie, but godot’s builtin sort already isn’t stable so this doesn’t really change anything.

Ah, right you are! That’s good to know. I was thinking Python…

1 Like