Jason Coon Jason Coon - 7 months ago 19
Python Question

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

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.

Answer

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.

Comments