
ab = { 'Swaroop' : 'swaroopch@byteofpython.info', 'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org', 'Spammer' : 'spammer@hotmail.com' }
Contact Swaroop at swaroopch@byteofpython.info Contact Matsumoto at matz@ruby-lang.org Contact Larry at larry@wall.org
Contact Guido at guido@python.org
We create the dictionary ab using the notation already discussed. We then access key/value pairs by specifying the key using the indexing operator as discussed in the context of lists and tuples. Observe that the syntax is very simple for dictionaries as well.
We can add new key/value pairs by simply using the indexing operator to access a key and assign that value, as we have done for Guido in the above case.We can delete key/value pairs using our old friend - the del statement. We simply specify the dictionary and the indexing operator for the key to be removed and pass it to thedel statement. There is no need to know the value corresponding to the key for this operation.
Next, we access each key/value pair of the dictionary using the items method of the dictionary which returns a list of tuples where each tuple contains a pair of items - the key followed by the value. We retrieve this pair and assign it to the variablesname andaddress correspondingly for each pair using thefor..in loop and then print these values in the for-block.
We can check if a key/value pair exists using thein operator or even thehas_key method of the dict class. You can see the documentation for the complete list of methods of thedict class usinghelp(dict).
Keyword Arguments and Dictionaries. On a different note, if you have used keyword arguments in your functions, you have already used dictionaries! Just think about it - the key/value pair is specified by you in the parameter list of the function definition and when you access variables within your function, it is just a key access of a dictionary (which is called the symbol table in compiler design terminology).