我正在尝试遍历以特定顺序定义的字典,但它总是以与我在代码中定义的顺序不同的顺序进行迭代。这只是我正在尝试做的一个基本示例。我正在迭代的字典更大,具有更复杂的命名键,并且不按字母/数字顺序排列。
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(),但这也不能维持我的顺序。
最佳答案
你应该使用 OrderedDict .它完全按照您想要的方式工作,但是您需要以这种方式定义它。或者,您可以按顺序排列键列表,然后遍历列表并访问字典。类似的东西:
level_lookup_order = ['PRIORITY_1', 'PRIORITY_2', ...]
for key in level_lookup_order:
if key in level_lookup:
do_stuff(level_lookup[key])
不过,维护起来会很痛苦,所以我建议您只使用 OrderedDict。
作为最后一个选项,您可以使用“常量”。喜欢,
PRIORITY_1 = 1
PRIORITY_2 = 2
...
lookup_order = {PRIORITY_1: 42, PRIORITY_2: 24, ...}
关于python - 如何按定义的顺序遍历 Python 字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17683151/