0

I have the following dictionaries in python 3. Both dictionaries have the same key and order, i.e., 'a', 'z', 'foo', 'b'. But each has a different value. I confirmed that both key-orders are always same. But does it depend on environments? I know we cannot usually fix the order of keys. I would like to know the key-order of different dictionaries with same keys'

dic1 = {'a': 0, 'z': 2, 'foo': 0, 'b': 0}
dic2 = {'a': 1, 'z': 0, 'foo': 8, 'b': 7}

for k, v in dic1.items():
    print(k, v)

for k, v in dic2.items():
    print(k, v)
jef
  • 3,890
  • 10
  • 42
  • 76

1 Answers1

0

The order of keys is not guaranteed to be stable before Python 3.7. However, in Python 3.7 and later, keys are guaranteed to be returned in the same order they were originally added to the dict.

See here for more details: Are dictionaries ordered in Python 3.6+?

If you want stable ordering in earlier versions of Python, you could use collections.OrderedDict.

Note that OrderedDict and the later Python dict do not sort the keys based on any property of the keys themselves (e.g. alphabetically), so neither of these meet your criterion that dicts with the same keys always return them in the same order. If you want that, you have a few options:

  • sort the keys before using (sorted(dct.keys()))
  • add the keys to a structure that keeps them sorted (e.g. a heapq) as you add them to the dict
  • define an arbitrary master ordering and use that for all the dicts (e.g. [f(d1[k], d2[k]) for k in d1])
  • use the SortedDict class from the sortedcontainers package: http://www.grantjenks.com/docs/sortedcontainers/sorteddict.html
Matthias Fripp
  • 17,670
  • 5
  • 28
  • 45