1

So, I construct a dictionary (with tuples) in python using this code:

d = { (x , x + 1) : x for x in range(0 , 10)}
print(d)

And I end up printing {(0, 1): 0, (1, 2): 1, (6, 7): 6, (5, 6): 5, (7, 8): 7, (8, 9): 8, (4, 5): 4, (2, 3): 2, (9, 10): 9, (3, 4): 3}

My question is: why doesn't it respect a specific order, the one I used for constructing the dictionary?

Andrei Manolache
  • 766
  • 1
  • 8
  • 17
  • 1
    You would appear to be using an older version of Python. CPython 3.6 preserved insertion order as an implication detail; Python 3.7 requires *all* implementations to preserve insertion order. If you are stuck using an older version, you need to use an `OrderedDict` from the `collections` module. – chepner Mar 16 '20 at 18:08
  • what version of python you have? – kederrac Mar 16 '20 at 18:09

1 Answers1

0

if your python version is < 3.6 you can use collections.OrderedDict to keep the insertion order:

from collections import OrderedDict

d = OrderedDict(((x , x + 1), x) for x in range(0 , 10))
d

output:

OrderedDict([((0, 1), 0),
             ((1, 2), 1),
             ((2, 3), 2),
             ((3, 4), 3),
             ((4, 5), 4),
             ((5, 6), 5),
             ((6, 7), 6),
             ((7, 8), 7),
             ((8, 9), 8),
             ((9, 10), 9)])
kederrac
  • 16,819
  • 6
  • 32
  • 55