如何按照定义的顺序遍历Python字典? [英] How to iterate over a Python dictionary in defined order?
问题描述
我试图遍历以特定顺序定义的字典,但是它总是以与我在代码中定义的顺序不同的顺序进行迭代.这只是我要尝试做的一个基本示例.我要遍历的字典更大,具有更复杂的命名键,并且不是字母/数字顺序.
I'm trying to iterate over a dictionary that I have defined in a specific order, but it always iterates in a different order than what I have defined in my code. This is just a basic example of what I'm trying to do. The dictionary I'm iterating over is much larger, has much more complexly named keys, and is not in alphabetical/numerical order.
level_lookup = \
{
'PRIORITY_1' : { 'level' : 'BAD', 'value' : '' },
'PRIORITY_2' : { 'level' : 'BAD', 'value' : '' },
'PRIORITY_3' : { 'level' : 'BAD', 'value' : '' },
'PRIORITY_4' : { 'level' : 'BAD', 'value' : '' },
'PRIORITY_5' : { 'level' : 'CHECK', 'value' : '' },
'PRIORITY_6' : { 'level' : 'CHECK', 'value' : '' },
'PRIORITY_7' : { 'level' : 'GOOD', 'value' : '' },
'PRIORITY_8' : { 'level' : 'GOOD', 'value' : '' },
}
for priority in level_lookup:
if( level_lookup[ priority ][ 'value' ] == 'TRUE' ):
set_levels += str( priority ) + '\n'
我需要在迭代过程中保留字典的顺序.我的订单不是按字母顺序排列的,因此按字母顺序进行排序实际上并没有帮助.有什么办法吗?我已经尝试过`level_lookup.items(),但这也不能维持我的订单.
I need the order that I define the dictionary in to be preserved during iteration. My order is not alphabetical, so sorting alphabetically wouldn't really help. Is there any way to do this? I've tried `level_lookup.items(), but that doesn't maintain my order either.
推荐答案
您应该使用 OrderedDict .它完全按照您想要的方式工作,但是您需要以这种方式进行定义.另外,您可以按顺序列出一个键列表,然后遍历该列表并访问字典.类似于以下内容:
You should use an OrderedDict. It works exactly the way you want it, however you need to define it that way. Alternatively, you can have a list of keys in order, and iterate through the list and access the dictionary. Something along the lines of:
level_lookup_order = ['PRIORITY_1', 'PRIORITY_2', ...]
for key in level_lookup_order:
if key in level_lookup:
do_stuff(level_lookup[key])
但是,这很难维护,因此我建议您只使用OrderedDict.
This will be a pain to maintain, though, so I recommend you just use the OrderedDict.
最后一个选择是,您可以使用常量".喜欢,
As a last option, you could use 'constants'. Like,
PRIORITY_1 = 1
PRIORITY_2 = 2
...
lookup_order = {PRIORITY_1: 42, PRIORITY_2: 24, ...}
这篇关于如何按照定义的顺序遍历Python字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!