How to iterate over a dictionary

Question:

In [1]: test = {}

In [2]: test["apple"] = "green"

In [3]: test["banana"] = "yellow"

In [4]: test["orange"] = "orange"

In [5]: for fruit, colour in test:
   ....:     print(fruit)
   ....:     
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-8930fa4ae2ac> in <module>()
----> 1 for fruit, colour in test:
      2     print(fruit)
      3 

ValueError: too many values to unpack

What I want is to iterate over test and get the key and value together. If I just do a for item in test: I get the key only.

An example of the end goal would be:

for fruit, colour in test:
    print(f"The fruit {fruit} is the colour {colour}")
Asked By: joedborg

||

Answers:

Use items() to get an iterable of (key, value) pairs from test:

for fruit, color in test.items():
    # do stuff

This is covered in the tutorial.

In Python 2, items returns a concrete list of such pairs; you could have used iteritems to get the same lazy iterable instead.

for fruit, color in test.iteritems():
    # do stuff
Answered By: Björn Pollex

The normal for key in mydict iterates over keys. You want to iterate items:

for fruit, colour in test.iteritems():
    print "The fruit %s is the colour %s" % (fruit, colour)
Answered By: Jochen Ritzel

Change

for fruit, colour in test:
    print "The fruit %s is the colour %s" % (fruit, colour)

to

for fruit, colour in test.items():
    print "The fruit %s is the colour %s" % (fruit, colour)

or

for fruit, colour in test.iteritems():
    print "The fruit %s is the colour %s" % (fruit, colour)

Normally, if you iterate over a dictionary it will only return a key, so that was the reason it error-ed out saying “Too many values to unpack”.
Instead items or iteritems would return a list of tuples of key value pair or an iterator to iterate over the key and values.

Alternatively you can always access the value via key as in the following example

for fruit in test:
    print "The fruit %s is the colour %s" % (fruit, test[fruit])
Answered By: Abhijit
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.