如何按定义的顺序迭代Python字典?

Pse*_*che 15 python dictionary loops

我正在尝试迭代我按特定顺序定义的字典,但它总是以与我在代码中定义的顺序不同的顺序迭代.这只是我正在尝试做的一个基本的例子.我正在迭代的字典要大得多,具有更复杂的命名键,并且不按字母/数字顺序排列.

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'
Run Code Online (Sandbox Code Playgroud)

我需要在迭代期间保存我定义字典的顺序.我的订单不是按字母顺序排列的,因此按字母顺序排序并不会有所帮助.有没有办法做到这一点?我试过`level_lookup.items(),但这也不能保持我的订单.

gcb*_*zan 9

你应该使用OrderedDict.它完全按照您的方式工作,但您需要以这种方式定义它.或者,您可以按顺序获得键列表,并遍历列表并访问字典.有点像:

level_lookup_order = ['PRIORITY_1', 'PRIORITY_2', ...]
for key in level_lookup_order:
    if key in level_lookup:
        do_stuff(level_lookup[key])
Run Code Online (Sandbox Code Playgroud)

但是,这将是一个难以维护,因此我建议您只使用OrderedDict.

作为最后一个选项,您可以使用'常量'.喜欢,

PRIORITY_1 = 1
PRIORITY_2 = 2
...
lookup_order = {PRIORITY_1: 42, PRIORITY_2: 24, ...}
Run Code Online (Sandbox Code Playgroud)


Dan*_*ocq 6

如果你使用按键排序的顺序没问题:

for key in sorted(level_lookup.keys()):
    ...
Run Code Online (Sandbox Code Playgroud)

如果dict提供给我的话,我通常会这样做,而不是我实例化的东西(而不是OrderedDict.