Issue
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?
Solution
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
Answered By - thefourtheye
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.