Python Tutorial: Dictionaries (Maps): Advanced features


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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s