How to get ordered output from dictionary in python?

I created a program using the python dictionary. In this simple program, I cannot understand the structure of the dictionary memory. And when I retrieve data from the dictionary at this time, the data is not retrieved in sequence.

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

He will give me this conclusion Two,Three,Five,Four , etc. If I want it to be ordered sequentially, what should I do?

+4
source share
2 answers

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

If you want to access the dictionary in key order, first get a list of keys, then sort, and then do the following:

 keys = Digit.keys() keys.sort() for i in keys: print Digit[i] 
+4
source

If you absolutely want to store ordered data, you can use OrderedDict as suggested by Berhan Khalid 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 
+1
source

Source: https://habr.com/ru/post/1494428/


All Articles