Possible Duplicate:
Python dictionary: are keys() and values() always the same order?
If i have a dictonary in python, will .keys and .values return the corresponding elements in the same order?
E.g.
foo = {'foobar' : 1, 'foobar2' : 4, 'kittty' : 34743}
For the keys it returns:
>>> foo.keys()
['foobar2', 'foobar', 'kittty']
Now will foo.values() return the elements always in the same order as their corresponding keys?
Answer. No, there is no guaranteed order for the list of keys returned by the keys() function. In most cases, the key list is returned in the same order as the insertion, however, that behavior is NOT guaranteed and should not be depended on by your program.
Yes. Starting with CPython 3.6, dictionaries return items in the order you inserted them.
values() changes depend on the data in it. That's why it is called unordered. Althought I stated the 'b' key first, it was allocated after 'a' . However, once the dict is set, it will always return the same order when called dict.
It's a dictionary subclass specially designed to remember the order of items, which is defined by the insertion order of keys. This changed in Python 3.6. The built-in dict class now keeps its items ordered as well.
It's hard to improve on the Python documentation:
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If
items()
,keys()
,values()
,iteritems()
,iterkeys()
, anditervalues()
are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of(value, key)
pairs usingzip(): pairs = zip(d.values(), d.keys()).
The same relationship holds for theiterkeys()
anditervalues()
methods:pairs = zip(d.itervalues(), d.iterkeys())
provides the same value for pairs. Another way to create the same list ispairs = [(v, k) for (k, v) in d.iteritems()]
So, in short, "yes" with the caveat that you must not modify the dictionary in between your call to keys()
and your call to values()
.
Yes, they will
Just see the doc at Python doc :
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.
Best thing to do is still to use dict.items()
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