2

I'm messing around with dictionaries for the first time and something's coming up that's confusing me. Using two lists to create a new dictionary, the order of the list terms for the key part seems to be wrong. Here's my code:

list1 = ["a", "b", "c", "d"]
list2 = [5,3,7,3] 
newDict = {list1[c]: number for c, number in enumerate(list2)}
print(newDict)

This gives me the following:

{'a': 5, 'd': 3, 'c': 7, 'b': 3}

Why is this happening? Surely the 'c' value getting terms from the list is going from 0 and upwards, so why isn't it creating the dictionary with the letters in the same order?

Thanks.

4 Answers4

3

For purposes of efficiency, traditional python dictionaries are unordered. If you need order, then you need OrderedDict:

>>> from collections import OrderedDict
>>> newDict = OrderedDict((list1[c], number) for c, number in enumerate(list2))
>>> print(newDict)
OrderedDict([('a', 5), ('b', 3), ('c', 7), ('d', 3)])

In Python 3.7, ordinary python dictionaries, implemented using a new algorithm, will be ordered. Until then, if you need order, use OrderedDict.

John1024
  • 109,961
  • 14
  • 137
  • 171
  • 2
    What makes you think they need that? They're only asking why it doesn't preserve order, not saying they want to. – Stefan Pochmann Feb 26 '18 at 01:41
  • 2
    @StefanPochmann Under normal rules of human behavior, the OP wouldn't take the time to ask about order unless, for some reason, it mattered to him. – John1024 Feb 26 '18 at 01:43
1

Python dictionaries don't preserve their order, but there's another data type that does: OrderedDict, from the collections module.

Sponja
  • 92
  • 5
1

Dictionaries are unordered. In fact, if you run your program on a different computer, you might get a different key ordering. This is an intentional feature of the built-in dictionary in python.

To understand why, take a look at this stackoverflow question.

nareddyt
  • 1,016
  • 10
  • 20
0

As of Python 3.7, dictionaries are insertion ordered. See this stackoverflow discussion Are dictionaries ordered in Python 3.6+?