Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

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.

like image 809
PseudoPsyche Avatar asked Jul 16 '13 17:07

PseudoPsyche


2 Answers

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, ...}
like image 105
gcbirzan Avatar answered Oct 19 '22 06:10

gcbirzan


If you're fine with using the key-sorted order:

for key in sorted(level_lookup.keys()):
    ...

That's what I generally do if the dict is provided to me, and not something I instantiate (rather than OrderedDict.

like image 41
Dan Lecocq Avatar answered Oct 19 '22 07:10

Dan Lecocq