Python Dictionaries

We can define dictionaries either literally or incrementally, and we can modify their elements at any time.  The only operation that error-prone is asking for an element that's not in the dictionary (will cause an error)....

>>> fred={'fname':'Fred','lname':'Weasley','age':17}
>>> fred['lname']
'Weasley'
>>> george={'fname':'George','lname':'Weasley','age':17}
>>> molly={'fname':'Milly','lname':'Weasley'}
>>> # we can correct (overwrite) that mistake...
>>> molly['fname']='Molly'
>>> #let's check on it...
>>> print molly
{'lname': 'Weasley', 'fname': 'Molly'}
>>> #notice that the order of the elements is not necessarily the order in which
>>> #   they were created (as in molly,above)
>>> 
>>> # now we can ask for george's age:
>>> print george['age']
17
>>> # in the name/value pairs that the dictionary has, the values need not be
>>> #   restricted to strings or numbers -- they can be many other things...
>>> fred['hobbies']=['pranks','slacking']
>>> print fred
{'lname': 'Weasley', 'age': 17, 'fname': 'Fred', 'hobbies': ['pranks', 'slacking']}
>>> # in fact, a value in one dictionary can be another dictionary:
>>> fred['parent']=molly
>>> fred
{'lname': 'Weasley', 'age': 17, 'parent': {'lname': 'Weasley', 'fname': 'Molly'}, 'fname': 'Fred', 'hobbies': ['pranks', 'slacking']}
>>> # what is fred's parent's last name?
>>> print fred['parent']['lname']
Weasley
>>> # how about a list of dictionaries...
>>> molly['children']=[fred,george]
>>> # what is molly's first child's fname?
>>> molly['children'][0]['fname']
'Fred'
>>> # what are his hobbies?
>>> molly['children'][0]['hobbies']
['pranks', 'slacking']
>>> # what are george's hobbies? (danger)
>>> molly['children'][1]['hobbies']

Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    molly['children'][1]['hobbies']
KeyError: 'hobbies'
>>> # unlike fred, george has no key called 'hobbies', and so the retrieval fails
>>> 
>>> # what is molly's first child's parent's first name?
>>> molly['children'][0]['parent']['fname']
'Molly'
>>> # does fred have hobbies?
>>> fred.has_key('hobbies')
True
>>> # does george have hobbies?
>>> george.has_key('hobbies')
False