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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With