How can i reverse my Dictionary in Godot?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By H0us5

I have a dictionary:
d = {‘one’: 1, ‘two’: 2, ‘three’: 3}
And i need reverse it to:
d = {‘three’: 3, ‘two’: 2, ‘one’: 1}
How i can do this?

:bust_in_silhouette: Reply From: jgodfrey

A Dictionary is inherently unordered. While the original insertion order will be preserved, there really is no mechanism to sort or reverse a dictionary - because it really has no order. This is not unique to GDScript. Like in many other languages, Godot’sDictionary is based on aHashmap internally (I assume).

That said, there are ways to get the result you’re after. Although, I’m curious about what led you to the key/value pair choices you show? For sorting or reversing, it’d seem to be much more useful if they were flip-flopped.

So, the key would be the int and the value would be the string. If your dictionary was structured like that, you could…

  • Get an array of keys via d.keys().
  • Sort that array and then reverse it.
  • Use the reversed array to drive a loop that would iterate over your dictionary in the order you need.