Ad

Saturday, March 24, 2018

Iterate through dictionary key and value The Pythonic Way

In Python 2.x you can iterate through a dictionary using:
for key, value in my_dict.iteritems():

Python 3: there is no more iteritems, items() achieve the same result which is returning an iterator - see below for more explanations.

for key, value in my_dict.items():
     print(key,value)

For Python 2.x

  • dict.items(): Return a copy of the dictionary’s list of (key, value) pairs.
  • dict.iteritems(): Return an iterator over the dictionary’s (key, value) pairs.
Some may say iterating through a large dictionary is not a good idea in the first place and is not Pythonic. 
See Python Anti-Pattern https://docs.quantifiedcode.com/python-anti-patterns/performance/not_using_iteritems_to_iterate_large_dict.html

Python doc has some suggestion to help handling legacy code in Python 2.x
https://www.python.org/dev/peps/pep-0469/

try:
    dict.iteritems
except AttributeError:
    # Python 3
    def itervalues(d):
        return iter(d.values())
    def iteritems(d):
        return iter(d.items())
else:
    # Python 2
    def itervalues(d):
        return d.itervalues()
    def iteritems(d):
        return d.iteritems()

No comments:

Post a Comment

Applying for jobs at the Lending Club

We tried to figure out Lending Club 's tech stack for 2019. Our analysis shows Lending Club asks for skills in Python, Tableau, SQL and ...