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():

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

Python doc has some suggestion to help handling legacy code in Python 2.x

except AttributeError:
    # Python 3
    def itervalues(d):
        return iter(d.values())
    def iteritems(d):
        return iter(d.items())
    # 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 ...