python - 如何按定义的顺序遍历 Python 字典?

标签 python loops dictionary

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

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/

相关文章:

c++ - 使用数组和结构的四分卫评级函数表现得很奇怪

java - 如果java中的条件!= null,有没有办法再次启动for循环

python - 转换字典列表中的列表的函数

python - 在 Windows 上安装 scipy 包时出错

python - 在虚拟环境中安装python站 pip 包

javascript - 将带有 AJAX 的 JSON 发送到 Flask 语法错误

python - 在 Python 2.6 中收集键/值对

python迭代仅选择包含特定字符的字符串

python - 循环遍历数组作为四个元素,但以连续的方式

javascript - 如何在 javascript 中对这个对象数组进行排序?