Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary: are keys() and values() always the same order?

Tags:

python

It looks like the lists returned by keys() and values() methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods).

For example:

>>> d = {'one':1, 'two': 2, 'three': 3} >>> k, v = d.keys(), d.values() >>> for i in range(len(k)):     print d[k[i]] == v[i]  True True True 

If you do not alter the dictionary between calling keys() and calling values(), is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.

like image 627
Jason Coon Avatar asked May 07 '09 14:05

Jason Coon


People also ask

Is the order of key-value pairs always the same in a dictionary?

Here you specify the key order upfront, the returned values will always have the same order even if the dict changes, or you use a different dict.

Are Python dictionary keys in order?

Answer. No, there is no guaranteed order for the list of keys returned by the keys() function.

Does dict values maintain order?

Standard dict objects preserve order in the reference (CPython) implementations of Python 3.5 and 3.6, and this order-preserving property is becoming a language feature in Python 3.7.

What is the difference between keys and values in dictionary?

Keys will be a single element. Values can be a list or list within a list, numbers, etc. More than one entry per key is not allowed ( no duplicate key is allowed) The values in the dictionary can be of any type, while the keys must be immutable like numbers, tuples, or strings.


2 Answers

Found this:

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

On 2.x documentation and 3.x documentation.

like image 195
nosklo Avatar answered Sep 19 '22 21:09

nosklo


Yes, what you observed is indeed a guaranteed property -- keys(), values() and items() return lists in congruent order if the dict is not altered. iterkeys() &c also iterate in the same order as the corresponding lists.

like image 40
Alex Martelli Avatar answered Sep 19 '22 21:09

Alex Martelli