Python 2 and 3 compatible way of iterating through dict with key and value
I would say is better to use future
module than implementing your own, many stuff is already done for you in minimalistic/optimized way:
from future.utils import viewitems
foo = [key for key, value in viewitems(some_dict) if value.get('marked')]
if you are curious how this viewitems()
is working, it's as simple as follows:
def viewitems(obj, **kwargs):
"""
Function for iterating over dictionary items with the same set-like
behaviour on Py2.7 as on Py3.
Passes kwargs to method."""
func = getattr(obj, "viewitems", None)
if not func:
func = obj.items
return func(**kwargs)
NB:
if compatibility with Python versions before 2.7 is
required then you should use iteritems()
:
from future.utils import iteritems
foo = [key for key, value in iteritems(some_dict) if value.get('marked')]
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