0
result = {}
a = ["a","b","c"]
b = [1, 2, 3]

for i in range(3):
  result[a[i]] = b[i]

print result

I expect to get following result: {'a': 1, 'b': 2, 'c': 3}

But the real one is {'a': 1, 'c': 3, 'b': 2}

What is the reason and how to fix it?

Paco
  • 4,520
  • 3
  • 29
  • 53
femalemoustache
  • 561
  • 6
  • 17
  • 1
    `dictionaries` are not ordered in python. Use `OrderedDict` https://docs.python.org/2/library/collections.html#collections.OrderedDict – Paco Apr 16 '15 at 14:57

2 Answers2

5

A python dictionary has an internal order that is randomized and that you shouldn't depend on.

If you would like to retain the order that you inserted objects in, you should use a collections.OrderedDict.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
2

dicts are unordered because keys aren't compared, their hashes are.

Use an OrderedDict from the collections module to maintain the order you inputted.

>>> import collections
>>>
>>> a = ["a", "b", "c"]
>>> b = [1, 2, 3]
>>>
>>> result = collections.OrderedDict(zip(a, b))
>>> result
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> dict(result) # no longer ordered
{'c': 3, 'a': 1, 'b': 2}
Navith
  • 929
  • 1
  • 9
  • 15
  • 2
    In the latest versions of python, it's actually even more complicated than using just the hash: http://stackoverflow.com/questions/14956313/dictionary-ordering-non-deterministic-in-python3 – Bill Lynch Apr 16 '15 at 15:01