Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2 and 3 compatible way of iterating through dict with key and value

I have the following list comprehension that only works in Python 2 due to use of iteritems():

foo = [key for key, value in some_dict.iteritems() if value['marked']]

I can't import any libraries. Is there a clean way of making this compatible on both Python 2 and 3?

like image 763
apscience Avatar asked Dec 20 '14 14:12

apscience


1 Answers

You can simply use dict.items() in both Python 2 and 3,

foo = [key for key, value in some_dict.items() if value['marked']]

Or you can simply roll your own version of items generator, like this

def get_items(dict_object):
    for key in dict_object:
        yield key, dict_object[key]

And then use it like this

for key, value in get_items({1: 2, 3: 4}):
    print key, value
like image 126
thefourtheye Avatar answered Nov 15 '22 20:11

thefourtheye