按顺序迭代字典

时间:2017-11-11 05:52:44

标签: python dictionary for-loop

我试图按照我创建字典的顺序遍历字典,例如,我希望它按此顺序打印名称。现在它以随机顺序打印。

我想要的订单: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)

2 个答案:

答案 0 :(得分:1)

使用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 :(得分:1)

Dictionaries 没有订单 因此您需要可以处理订单的外部类。像OrderedDict模块中可用的collections之类的东西,它在基础dict类上形成一个包装类,提供额外的功能以及dict的所有其他基本操作。

示例:

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