1

I have a dictionary like this say:

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

Now 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?

Nam G VU
  • 33,193
  • 69
  • 233
  • 372
AKKI
  • 63
  • 1
  • 8
  • Use [`collections.OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict) – Anand S Kumar Jul 30 '15 at 04:48
  • 3
    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

6

Use OrderedDict class. Example below.

from collections import OrderedDict

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