为什么这个python字典是使用setdefault()无序创建的?

时间:2012-08-02 19:59:16

标签: python dictionary for-loop setdefault

我刚开始玩Python(VBA背景)。为什么这本字典无序创建?不应该是:1,b:2 ......等等?

class Card:
def county(self):
    c = 0
    l = 0
    groupL = {}  # groupL for Loop
    for n in range(0,13):
        c += 1
        l = chr(n+97)
        groupL.setdefault(l,c)
    return groupL

pick_card = Card()
group = pick_card.county()
print group

这是输出:

{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12}

或者,是否只是按顺序打印?

1 个答案:

答案 0 :(得分:15)

字典在python中没有顺序。换句话说,当您遍历字典时,键/项被“产生”的顺序​​不是您将它们放入字典的顺序。 (在不同版本的python上尝试你的代码,你可能得到不同的有序输出)。如果你想要一个有序的字典,你需要一个collections.OrderedDict,直到python 2.7才会引入。{1}}。如果您使用的是旧版本的python,则可以在ActiveState上找到等效的食谱。但是,通常只对项目进行排序(例如sorted(mydict.items())

就足够了

编辑按要求,OrderedDict示例:

from collections import OrderedDict
groupL = OrderedDict()  # groupL for Loop
c = 0
for n in range(0,13):
    c += 1
    l = chr(n+97)
    groupL.setdefault(l,c)

print (groupL)