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?
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?
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
.
dict
s 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}