Dictionary: Are keys() and values() guaranteed to correspond?

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

If I get the list of keys of a dictionary by calling keys(), and I get the list of values by calling values(), is it guaranteed that the ordering of the two lists corresponds with each other? In other words, values[n] == dictionary[keys[n]] for all possible values of n?

:bust_in_silhouette: Reply From: godot_dev_

I am not sure, but if your goal is to achieve this, you could create the values array by iterating over all the keys and appending the value of the n th key to the values array as follows:

var values = []
for k in dic.keys():
:bust_in_silhouette: Reply From: evpevdev

Dictionaries are unordered, so calling keys() and values() will not correspond with each other. In fact, if you call keys() twice, the list will be in a different order each time. What you can do is get the list of keys using keys = dict.keys(), then to get the key and value pair for a specific index you can just use key = keys[i] and value = dict[keys[i]]. This way you only need to keep track of one list, not two.

If you really do need a keys and values list, you can do what @godot_dev_ did in his answer and loop through all the keys and append their values to a new list.

EDIT: As @frogeyguy mentioned, dictionaries in Godot are actually ordered, so calling keys() and values() should correspond as long as you don’t change the dictionary in between the calls, and printing the dictionary twice in a row will be the same.

Is that really true? The docs do mention that insertion order is preserved for dictionaries.

frogeyeguy | 2023-04-20 17:51

I’m not sure then. I was just assuming they were the same as python dictionaries, which are unordered.

evpevdev | 2023-04-20 22:30

Okay after trying it, Godot Dictionaries do preserve the order and calling keys() and values() matches up.

evpevdev | 2023-04-20 22:39