0

I have write down this program in python

Create a dictionary

 a = { 'a':'b', 'x':'x', '2':'2' }

After run loop

 for c in a:
   a[c]

result is

'2'
'b'
'x'

I expect, there should be "b x 2" result but it sort automatically, Why happen this and how can i control this?

jatin
  • 11
  • 1

1 Answers1

1

Dictionary in python is not ordered , the order in which you are receiving the keys is basically dependent on the python implementation. Your code should not depend on it.

From documentation -

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)


If order is important for your program, use collections.OrderedDict . Example -

>>> from collections import OrderedDict
>>> d = OrderedDict([('a','b'),('x','x'),('2','2')])
>>> for c in d:
...     d[c]
...
'b'
'x'
'2'
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176