4

我使用 python Dictionary 创建了一个程序。在这个简单的程序中,我无法理解字典的内存结构。当我当时从字典中检索数据时,数据没有按顺序检索。

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

它会给我这样的输出等Two,Three,Five,Four。如果我希望它按顺序排序,我该怎么办?

4

2 回答 2

4

字典在 Python 中是任意排序的。订单无法保证,您不应依赖它。如果您需要有序集合,请使用其中之一OrderedDict或列表。

如果您想按键顺序访问字典,请首先获取键列表,然后对其进行排序,然后逐步执行:

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

for i in keys:
   print Digit[i]
于 2013-07-31T06:41:21.187 回答
1

如果您绝对想存储有序数据,您可以使用 Burhan Khalid 在他的回答中建议的 OrderedDict :

>>> 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
于 2013-07-31T07:00:20.297 回答