0

Could you please tell me whats the difference between python dict on below two cases. First one prints the data in correct order but on second iteration P6 take precedence over P5. What will be the reason?

>>> a=["P3", "P4"]
>>> devices_by_dc = {}
>>> for b in a:
...   devices_by_dc[b] = {}
>>> print devices_by_dc
{'P3': {}, 'P4': {}}


>>> a=["P5", "P6"]
>>> devices_by_dc = {}
>>> for b in a:
...   devices_by_dc[b] = {}
{'P6': {}, 'P5': {}}

2 Answers2

0

In Python, dictionaries are not ordered, they are a set-like objects. Therefore the order of printing it is completely random.

Consider dict.keys(). That is a set. So basically when you do

print(dict)

what actually happens is

for key in dict.keys():
    str_out = ' \'{0}\': {1},'.format(key, dict[key]
print '{{ {0} }}'.format(str_out[:-1])

And since dict.keys() is a set, the order of selecting keys is random.

If you want to introduce order into dictionary, then instead of dict use collections.OrderedDict as suggested in the comment to the question. Don't forget to import collections.

campovski
  • 2,979
  • 19
  • 38
0

Dictionaries in python are not ordered by default. You can use an OrderedDict instead.

import collections

devices_by_dc = collections.OrderedDict()
for b in a:
    devices_by_dc[b] = {}
arjunattam
  • 2,679
  • 18
  • 24