Iterating over dictionary values

If we want to iterate over only the values, we can use the values() dictionary method. This returns an object which provides an iterable view onto the dictionary values without causing the values to be copied:

>>> for value in colors.values():
... print(value)
...
#B22222
#B03060
#7FFFD4
#DEB887
#F0FFF0
#A0522D
#DEB887
#6495ED

There is no efficient or convenient way to retrieve the corresponding key from a value, so we only print the values

In the interests of symmetry, there is also a keys() method, although since the iterating over the dictionary object directly yields the keys, this is less commonly used:

>>> for key in colors.keys():
... print(key)
...
firebrick
maroon
aquamarine
burlywood
honeydew
sienna
chartreuse
cornflower

 

..................Content has been hidden....................

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