Sorting: more loop operations of maps

Suppose, we have the following map:

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> D
{'a': 1, 'c': 3, 'b': 2}

We can create a list of keys of a map, then use a for loop to treat it as a sequence:

>>> Ks = D.keys( ) # Unordered keys list
>>> Ks
['a', 'c', 'b']
>>> Ks.sort( ) # Sorted keys list
>>> Ks
['a', 'b', 'c']
>>> for key in Ks: # Iterate though sorted keys
print key, '=>', D[key]
a => 1
b => 2
c => 3

Checking existance of a key:

Fetching a non-existant key is error. Consider the following code snippet:

>>> D
{'a': 1, 'c': 3, 'b': 2}
>>> D['e'] = 99 # Assigning new keys grows dictionaries
>>> D
{'a': 1, 'c': 3, 'b': 2, 'e': 99}
>>> D['f'] # Referencing one is an error
...error text omitted...
KeyError: 'f'


We can use following method to check whether a key exists:

>>> D.has_key('f')
False
>>> if not D.has_key('f'):
print 'missing'
missing