Working with Dictionaries
What is a Python
dictionary?
A dictionary
is a data structure that lets you associate a key with a value
For example,
you could assign a name (key) to a telephone number (value)
In Python,
you can do it like this:
>>>
tel_nums = {'Bob':'555-1111', 'Mary':'555-2222'}
>>>
tel_nums
{'Bob':'555-1111',
'Mary':'555-2222'}
In this
example, tel_nums is a dictionary with 2 items
An item is a
key-value pair separated by a colon
We can refer
to values in the dictionary by their keys like this:
>>>
tel_nums['Bob']
'555-1111'
>>>
tel_nums['Mary']
'555-2222'
So what?
If you know
the key of the value you�re looking for, you can often find it much faster
using a dictionary than by some other method
Let�s assume
you had a list set up like this to store names and numbers:
>>>
tel_num_list = ['Bob', '555-1111', \
�� �Mary', '555-2222', 'Jill', '555-1234']
>>>
tel_num_list
['Bob',
'555-1111', 'Mary', '555-2222', 'Jill', '555-1234']
How might you
find Jill�s phone number?
You could
search through the list for Jill�s name, then select the next item
Try this in
Sublime:
def getPhoneNum(theList, name):
� pos
= 0
� for n in theList:
��� pos
+= 1
��� if n == name:
������ print 'found ' +
name + '\'s phone number at pos ' + str(pos)
������ return theList[pos]
tel_num_list = ['Bob', '555-1111', 'Mary', '555-2222', \
'Jill',
'555-1234']
print 'Mary: ', getPhoneNum(tel_num_list, 'Mary')
I get the
following output:
Mary:� found Mary's phone number at pos 3
555-2222
This works
but is difficult to understand and will take a lot longer to perform on large
data sets�use the dictionary approach instead!!
Using dictionaries as
keyword arguments to functions (kwargs)
The code here makes use of dictionaries as keyword
argument lists (and other argument types as well)
Professional
python programmers make extensive use of the **kwargs technique
Here is a typical use of kwargs in an imported library module (the acorr()
function in the pyplot library)
Hash codes
Dictionaries
implement hash codes�a fundamental
type of algorithm for classifying a value with a key
You can read about hash
codes here and in many other places
This link
refers specifically to Java but the idea of a hash code is generic to all
languages