Dictionaries

A Dictionary contains a group of key/value pairs  -- like the name of a person (the key) and her GPA (the value), or the name of a department at Stuy (as the key) and the list of teachers in that department (the value).  There are restrictions on what kinds of datatypes are allowed to be keys in a dictionaries -- for instance, lists are not allowed but tuples are.  We will typically use strings for keys.  However, there are almost no restrictions on values -- they can be strings, numbers, lists, other dictionaries, dictionaries of dictionaries, elephants, etc.

For instance, we can keep track of who/what people like:

we_like={'Harry':'Ginny','Ron':'Hermione','Voldy':'a nose'}

But we can get more strange:

huh={'Bernie':'revolution','Cruz':['humor','straight eyebrows'],'Trump':10000000000.13}

print(huh['Cruz'])
['humor','straight eyebrows']

Here are some dictionary operations:

>>> # create an empty dictionary
>>> fred={}
>>> # add two entries
>>> fred['George']=45
>>> fred['Harry']='blob'
>>> print(fred)
{'Harry':'blob','George':45}
>>> # notice that there's no guaranteed order of key/value pairs inside the dictionary
>>> # retrieve one of the entries
>>> print(fred['Harry'])
blob
>>> # try to retrieve an entry that's not in the dictionary
>>> print(fred['Ginny'])
KeyError: 'Ginny'
>>> # if you're not sure that the key is in the dictionary, check before trying to retrieve it...
>>> if 'George' in fred:
print(fred['George'])
45
>>> # or use the .get() method, which gives you a default value if the key you're asking for is not in the dictionary...
>>> print(fred.get('Ginny','blah'))
'blah'
>>> print(fred.get('Harry','dorp'))
blob
>>> # add more entries (notice that several entries can have the same value)
>>> fred['Voldy']='blob'
>>> fred['Peter']=42
>>> # delete an entry
>>> del fred['George']
>>> print(fred)
{'Voldy':'blob','Harry':'blob','Peter':42}
>>> # get a list of all the keys -- be sure to convert fred.keys() into a list using the list() function
>>> the_keys=list(fred.keys())
>>> print(the_keys)
['Voldy','Harry','Peter']
>>> # print the contents of the dictionary nicely, in alphabetical order by name
>>> the_keys.sort() # put the keys in alpha order
>>> for akey in the_keys:
print ('%s loves %s' % (akey,str(fred[akey]))) # make sure the value is a string
Harry loves blob
Peter loves 42
Voldy loves blob
>>>

Lots more dictionary methods...  (this list is for Python 2.7, but most of the methods are also available in Python 3.8 except for dict.has_key())