1

When I access the elements in 2 dictionaries that are mapped using the same keys, do they get accessed in the same order at all times?

For example, say I have dictionary 1 and dictionary 2.

Dictionary 1:
Key 1: a1
Key 2: a2

Dictionary 2:
Key 1: b1
Key 2: b2

If I access the elements of these 2 dictionaries using a for loop, using something like this: for element in dictionary.values():

Can I then match up a1:b1 and a2:b2?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user3666471
  • 907
  • 11
  • 24
  • 2
    If they have identical keys, just iterate over one's keys then get the values from both for that key. Why rely on order? – jonrsharpe Aug 07 '14 at 19:53
  • I am fairly certain that you can count on the fact that 2 successive calls to dict.values() without any other call on that dict will yield the same result. But that is not a feature of the dict, it just so happens because there is no reason for anything else to happen – njzk2 Aug 07 '14 at 19:56
  • Essentially: consider dictionaries to be completely without order. Pretend every call to `__iter__` returns `random.choice(self.keys())` ;) – Adam Smith Aug 07 '14 at 20:10

4 Answers4

3

No, there is no such guarantee.

Here is a concrete example that demonstrates this:

>>> dict1 = {str(i):None for i in range(10000)}
>>> dict2 = {}
>>> dict2.update(dict1)

The dictionaries are equal but the keys are returned in different order:

>>> dict1 == dict2
True
>>> dict1.keys() == dict2.keys()
False

If you want the same traversal order, you could parallel iterate over sorted(dict1.keys()) and sorted(dict2.keys()):

>>> sorted(dict1.keys()) == sorted(dict2.keys())
True

Depending on your use case (i.e. the insertion order), collections.OrderedDict might also be useful.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

Dictionaries in python are without order. For a datatype that keeps order: use a list.

From the official python docs:

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

For more information on why are they unordered, check out this answer here: https://stackoverflow.com/a/526131/2259303

Community
  • 1
  • 1
agconti
  • 17,780
  • 15
  • 80
  • 114
0

You're not guaranteed any ordering in a dictionary.

But you can get sorted key, value pairs in lists of tuples. For instance:

chars = {'a':0, 'c':2, 'f':6, 'h':8}
sorted_chars = sorted(chars.iteritems(), key=operator.itemgetter(1)) 
# list of tuples sorted by value => [('a', 0), ('c', 2), ('f', 6), ('h', 8)]
celeritas
  • 2,191
  • 1
  • 17
  • 28
0

You could try using OrderedDict to impose some order to your dictionaries.

from collections import OrderedDict

d1 = OrderedDict([('ka1','a1'), ('ka2','a2')])
d2 = OrderedDict([('kb1','b1'), ('kb2','b2')])

for k1, k2 in zip(d1, d2):
    print d1[k1], d2[k2]

will print out:

a1 b1
a2 b2
jh314
  • 27,144
  • 16
  • 62
  • 82