Skip to content Skip to sidebar Skip to footer

I Know Python Dict Is Order Less But Why I Am Getting Keys In Same Order "always"

I have a dict named tmp: >>> tmp {1: 'ONE', 2: 'TWO', 3: 'THREE'} >>> type(tmp) I iterated through this dict twenty times and on all iteratio

Solution 1:

You don't modify tmp between calls to tmp.keys(), so the order of the keys never changes.

From the docs:

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). The same relationship holds for the iterkeys() and itervalues() methods: pairs = zip(d.itervalues(), d.iterkeys()) provides the same value for pairs. Another way to create the same list is pairs = [(v, k) for (k, v) in d.iteritems()].

Solution 2:

Because otherwise, this wouldn't work:

for key, value in zip(d.keys(), d.values()):
    ...

And various similar problems.

Python's dict and set types are guaranteed to have the same iteration order as long as the dict/set isn't modified. Try adding other values to tmp and chances are you'll get a different order next time.

(However, note that small integers as keys are not a particularly great example of how this works — small integers hash to themselves in CPython, so they're probably more likely to pop out in numerical order. Try some strings.)

Solution 3:

Upon creating a dict, python creates its own order. Everytime you call the .keys() or .values() or .items(), you will get the result unordered in the same order everytime as long as you don't modify the dictionary. Hope that makes sense.

As you can see in the example below, even though I create the dictionary with a specific order, python reorders the dictionary. However, after that, the order always stays the same (as long as you don't modify the dictionary).

a = {'apple' : 'fruit', 'car' : 'vehicle', 'onion' : 'vegetable'}

print a

for i in range(5):
    print a.keys()

[OUTPUT]
{'car': 'vehicle', 'apple': 'fruit', 'onion': 'vegetable'}
['car', 'apple', 'onion']
['car', 'apple', 'onion']
['car', 'apple', 'onion']
['car', 'apple', 'onion']
['car', 'apple', 'onion']

Solution 4:

Since python dict is implemented as Hash Table, the order of key is based on its hash value, which decides which slot is used to store 'key/value' pair.

For integer value as the key, the hash value is simply the integer itself

>>>map(hash, [1,2,3])
[1,2,3]

Here what you use as key is consecutive int, their hash value is also consecutive, there is high chance that the underneath hash algorithm choose the consecutive slots to store 'key/value' pairs, that's why you see the same order as you create the dict. Here is a simple counterexample:

>>>tmp = {1:1, 5:5, 10:10}>>>tmp.keys()
[1, 10, 5]

And of course during the loop, you don't modify the dictionary, which will not cause hash table to get resized, so the order remains.

>>> foriinrange(5):
...   printtmp.keys()
[1, 10, 5][1, 10, 5][1, 10, 5][1, 10, 5][1, 10, 5]

If you are interested in the detailed implementation in Python, check this nice article: Python dictionary implementation

Post a Comment for "I Know Python Dict Is Order Less But Why I Am Getting Keys In Same Order "always""