Iterating over key-value pairs

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 => #B22222
maroon => #B03060
aquamarine => #7FFFD4
burlywood => #DEB887
honeydew => #F0FFF0
sienna => #A0522D
chartreuse => #DEB887
cornflower => #6495ED
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset