+1 vote

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

in Engine by (290 points)

1 Answer

0 votes

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).

by (27,952 points)
edited by

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!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.