Iterating over dictionary keys

As we have seen in an earlier chapter, dictionaries are iterable and so can be used with for-loops. The dictionary yields only the key on each iteration, and it's up to us to retrieve the corresponding value by lookup using the square-brackets operator:

>>> colors = dict(aquamarine='#7FFFD4', burlywood='#DEB887',
... chartreuse='#7FFF00', cornflower='#6495ED',
... firebrick='#B22222', honeydew='#F0FFF0',
... maroon='#B03060', sienna='#A0522D')
>>> for key in colors:
... print("{key} => {value}".format(key=key, value=colors[key]))
...
firebrick => #B22222
maroon => #B03060
aquamarine => #7FFFD4
burlywood => #DEB887
honeydew => #F0FFF0
sienna => #A0522D
chartreuse => #7FFF00
cornflower => #6495ED

Notice that the keys are returned in an arbitrary order which is neither the order in which they were specified nor any other meaningful sort order.

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

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