How To Iterate Over A Dictionary
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 frui
Solution 1:
In Python 2 you'd do:
forfruit, color in test.iteritems():
# do stuff
In Python 3, use items() instead (iteritems() has been removed):
forfruit, color in test.items():
# do stuff
This is covered in the tutorial.
Solution 2:
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 intest:
print"The fruit %s is the colour %s" % (fruit, test[fruit])
Solution 3:
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)
Post a Comment for "How To Iterate Over A Dictionary"