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}")
Use
items()to get an iterable of(key, value)pairs fromtest:This is covered in the tutorial.
In Python 2,
itemsreturns a concrete list of such pairs; you could have usediteritemsto get the same lazy iterable instead.