June 2017
Beginner
352 pages
8h 39m
English
Often though, we want to iterate over the keys and values in tandem. Each key-value pair in a dictionary is called an item and we can get hold of an iterable view of items using the items() dictionary method. When iterated the items() view yields each key-value pair as a tuple. By using tuple unpacking in the for-statement we can get both key and value in one operation without the extra lookup:
>>> for key, value in colors.items():... print("{key} => {value}".format(key=key, value=value))...firebrick => #B22222maroon => #B03060aquamarine => #7FFFD4burlywood => #DEB887honeydew => #F0FFF0sienna => #A0522Dchartreuse => #DEB887cornflower => #6495ED
Read now
Unlock full access