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.
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.
Answer. No, there is no guaranteed order for the list of keys returned by the keys() function.
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.
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.
Found this:
If
items()
,keys()
,values()
,iteritems()
,iterkeys()
, anditervalues()
are called with no intervening modifications to the dictionary, the lists will directly correspond.
On 2.x documentation and 3.x documentation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With