python - If dictionaries aren't ordered, why do two dictionaries with the same key names return values in the same order? -


this question has answer here:

if make 2 dictionaries same keys, seems return values in same order, though dictionaries aren't ordered. instance, if this:

dict1 = {"a":1, "b":2, "c":3, "d":4} dict2 = {"a":10, "b":20, "c":30, "d":40}  zip(dict1.values(), dict2.values()) 

it gives "desired" output:

[(1, 10), (3, 30), (2, 20), (4, 40)] 

why happen? can count on 2 dictionaries same keys having values ordered in same way?

keys in same order, there no guarantee. if there no hash value collisions keys in order. there can collisions, , in case order of insertion affect order of keys.

for example, 1 , 65 generate hash collisions due dictionaries having sizes powers of 2 (on machine, @ least). 1 % 8 == 65 % 8, 2 keys map same hash table bucket.

>>> {1: 'foo', 65: 'bar'} {1: 'foo', 65: 'bar'} >>> {65: 'bar', 1: 'foo'} {65: 'bar', 1: 'foo'} 

identical dictionaries different insertion order means keys ordered differently.

>>> {1: 'foo', 65: 'bar'} == {65: 'bar', 1: 'foo'} true 

this example happens (not) work on python version. python language not specify how keys map hash buckets.


Comments