0

I have two lists which I'm mapping into a dictionary.

The two lists are-

a = ['a','b','c','d'] and b = [1,2,3,4] .

When I run the command

>>> d = dict(zip(a,b))
>>> d

I get

{'a': 1, 'c': 3, 'b': 2, 'd': 4}

whereas the expected value is {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Why this change in the order of the keys?

deathstroke
  • 526
  • 12
  • 33

2 Answers2

4

There is no inherent "obvious" order in the keys of a dict. Admittedly, the docs only spell it out for CPython, but also note

If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

which says by omission that otherwise they might change.

(Note that there is an order, but it involves the hashes of the keys, so it's not as easy as "a before b", and in particular, since a few years back, it is liable to change with each new call of the executable.)

Ulrich Schwarz
  • 7,598
  • 1
  • 36
  • 48
3

There is no order in a dictionary.

{'a': 1, 'b': 2, 'c': 3, 'd': 4} == {'a': 1, 'c': 3, 'b': 2, 'd': 4}
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55