在ord中遍历字典

2024-10-04 05:26:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着按我创建字典的顺序迭代字典,例如,我希望它按这个顺序打印名字。现在它以随机顺序打印。在

我要的菜: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)

Tags: 代码nameselffor字典顺序名字many
2条回答

{a1}维护字典顺序

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)

Dictionaries没有顺序,因此您需要可以处理顺序的外部类。在^{}模块中提供了类似^{}的东西,它在基dict类上形成了一个包装类,提供了额外的功能以及{}的所有其他基本操作。在

示例:

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

相关问题 更多 >