1

I have a dictionary like this say:

a = {'first': 1, 'second': 2, 'third': 3}

No when I print it prints in an very random order. Whereas I need it to preserve the order always. How can I go about doing this in python???

Anand S Kumar
  • 82,977
  • 18
  • 174
  • 164
AKKI
  • 53
  • 1
  • 8
  • Use [`collections.OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict) – Anand S Kumar Jul 30 '15 at 04:48
  • 2
    As a much delayed follow-up, dictionaries are now order preserving in Python 3.6 as an implementation detail, and as a language feature in 3.7 and above. [A great write-up is found in this answer.](https://stackoverflow.com/a/39537308/211827) – amcgregor Feb 06 '19 at 15:51

1 Answers1

5

Use OrderedDict class. Example below.

from collections import OrderedDict

dict=OrderedDict()
dict['first']=1
dict['second']=2
dict['third']=3
dict
user353gre3
  • 2,703
  • 4
  • 23
  • 27