Aniket Bhatt
Aniket Bhatt

Reputation: 105

How to get an ordered output from a Dictionary in python?

I have created a program using python Dictionary. In this simple program i can not understand the memory structure of the dictionary. And when I retrieve the data from the dictionary at that time the data is not retrieve in the sequence.

Digit = {1 : One, 2: Two,3: Three,4: Four,5: Five,6: Six,7: Seven,8: Eight,9: nine,0: Zero}
print Digit

It will give me the output like thatTwo,Three,Five,Four etc. If I want it ordered in sequence what do I have to do ?

Upvotes: 4

Views: 135

Answers (2)

roman
roman

Reputation: 117636

If you absolutely want to store ordered data, you could use OrderedDict as Burhan Khalid suggested in his answer:

>>> from collections import OrderedDict
>>> Digit = [(1, "One"), (2, "Two"), (3, "Three"), (4, "Four"), (5, "Five"), (6, "Six"), (7, "Seven"), (8, "Eight"), (9, "Nine"), (0, "Zero")]
>>> Digit = OrderedDict(Digit)
>>> Digit
OrderedDict([(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five'), (6, 'Six'), (7, 'Seven'), (8, 'Eight'), (9, 'Nine'), (0, 'Zero')])
>>> for k,v in Digit.items():
...     print k, v
... 
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
7 Seven
8 Eight
9 Nine
0 Zero

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174758

Dictionaries are arbitrarily ordered in Python. The order is not guaranteed and you should not rely on it. If you need an ordered collection, use either OrderedDict or a list.

If you want to access the dictionary in key order, first get a list of the keys then sort it and then step through that:

keys = Digit.keys()
keys.sort()

for i in keys:
   print Digit[i]

Upvotes: 4

Related Questions