遍历字典的顺序问题

3

我希望能按照创建字典的顺序遍历字典,例如,我想以以下顺序打印名称。目前它以随机顺序打印。

我想要的顺序:ExtraClick,AutoClick,PackCookies,BakeStand,GirlScouts

代码:

self.how_many_buildings = {'ExtraClick': 0,
                               'AutoClick': 0,
                               'PackCookies': 0,
                               'BakeStand': 0,
                               'GirlScouts': 0}
for name in self.how_many_buildings:
    print(name)

1
https://docs.python.org/2/library/collections.html#collections.OrderedDict - Albin Paul
2个回答

4
使用 OrderedDict 来保持字典的顺序。
from collections import OrderedDict

self.how_many_buildings = OrderedDict(('ExtraClick', 0),
                                      ('AutoClick', 0),
                                      ('PackCookies', 0),
                                      ('BakeStand', 0),
                                      ('GirlScouts': 0))
for name in self.how_many_buildings:
    print(name)

1

字典 没有顺序,因此您需要外部类来处理顺序。例如 OrderedDict,它是 collections 模块中可用的包装器类,基于 dict 类提供额外的功能以及所有其他基本操作。

示例:

>>> from collections import OrderedDict
>>> d = OrderedDict( [('a',1) , ('b',2) , ('c',3)] )
>>> for key in d: 
        print(key)    
=>  a
    b
    c

当您从字典文字创建一个OrderedDict时,由于参数是无序的,您不知道项目最终会以什么顺序结束。为了避免这种情况,您应该使用有序可迭代对象,如listtuple或生成器来控制返回的字典内容的顺序。 - martineau
@martineau:已更新。 - Kaushik NP

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接