Iterating over a dictionary.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By stubbsy345
:warning: Old Version Published before Godot 3 was released.

I am currently iterating over a dictionary in order to print some values to labels. However, the dictionary does not iterate in the order which I have written it out. Is there a way of forcing it to do this? Bear in mind I still need to access the dictionary. I tried:

for item in range(0, dict.size()): 
          label.set_text(dict[item])

Although this would iterate in the correct order. It does not allow me to access the dict as item is an integer and not the key anymore.

Thanks in advance.

Matt

:bust_in_silhouette: Reply From: Zylann

In general, very few programming languages provide Dictionary structures that are ordered by insertion time. That’s because dictionaries are intented for fast key=>value access, not iteration in order. For that purpose, Arrays are often used instead.

However, Godot Dictionaries got insertion-order iteration (like you expect), but I can’t tell if that was added for 2.1.2 or 3.0. If it’s in 2.1.2 then it would be a bug, unless I miss something.

The code you wrote won’t work. On an array it will, but not on dictionaries (unless your keys are really integers going from 0 to size, but then using an array would be better).

Oh right thanks,

I got around it by having a dictionary item that was an array of the keys so that I could make the information appear in the order I wanted.

Thanks for replying!

stubbsy345 | 2017-04-03 10:59