python字典遍历 没有顺序,如何按照定义的顺序遍历Python字典?

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'

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.

解决方案

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])

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, ...}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值