Python Dictionaries “Finger Exercises”
A list is essentially a mapping from its indices 0…n-1,
which are all integers, to some values. I.e., given an integer i,
you can find a corresponding value l[i]
.
A dictionary is much the same, except that it allows you to map from
(almost) any kind of value, not just integers.
Examples
As an example, we could have the following dictionary:
-
aDict = {4: "hi", True: 24, "silly": ["very", "very", "very"]}
-
Now, look at each of the values, in turn:
print aDict[4] print aDict[True] print aDict["silly"]
In this example, 4
, True
, and "silly"
are known as the keys, while
"hi"
, 24
, and ["very", "very", "very"]
are the corresponding values.
Since the keys are not necessarily nicely ordered like the indices of a list, the dictionary itself is not considered to have an order. It may display in a different order than you entered.
-
print aDict
What might we use them for? Our motivating example is for word counts. Thus, the keys would be strings, and the values would be integers. Ignoring punctuation and capitalization, the counts for the Beatles' Love Me Do would be
-
counts = { "love": 24, "me": 14, "do": 14, "you": 9, "know": 2, "I": 2, "I'll": 4, "always": 4, "be": 4, "true": 4, "so": 4, "please": 4, "whoa": 5, "yeah": 1, "oh": 1, "someone": 3, "somebody": 1, "to": 2, "new": 1, "like": 1}
Another text-based example would be a substitution cipher, where we want to map each letter to its coded version.
-
cipher = {"a": "n", "b": "f", "c": "y", "d", "l", "e": "a", "f": "r", … }
Creating dictionaries
As seen in the previous examples, we can create a dictionary using curly braces to enclose the key:value pairs, separated by commas. An empty dictionary, with no key:value pairs, just has the curly braces.
-
{ }
-
Or, alternatively:
dict()
We can also create a dictionary by converting a list of pairs:
-
pairs = [(4,"hi"), (True,24), ("silly",["very","very","very])] dict(pairs)
Operations on dictionaries
As previously illustrated, we can look for the value associated with some key.
-
aDict[4]
-
See what happens when you look up a key that isn't used by the
dictionary:
aDict["Not there"]
We can change a dictionary by changing or creating a key/value pair:
-
aDict[4] = 17 aDict["Not there"] = "over here" aDict
Write a function that takes a list and returns the corresponding dictionary,
where the keys are the list indices.
I.e., given a list ["cat","dog","shark"]
, it returns
{0: "cat", 1: "dog", 2: "shark"}
.
-
A basic version, looping over the list:
def list2dict(aList): """Returns a dictionary of the given list elements, with the list indices as keys.""" aDict = {} for i in range(len(aList)): aDict[i] = aList[i] return aDict
-
For list comprehension aficionados, the loop can be collapsed into a single
line of code:
def list2dict(aList): """Returns a dictionary of the given list elements, with the list indices as keys.""" return dict([(i,aList[i]) for i in range(len(aList))])
-
For COMP 130 students, a slicker version using
zip
:def list2dict(aList): """Returns a dictionary of the given list elements, with the list indices as keys.""" return dict(zip(range(len(aList)),aList))
-
A similar way with a list comprehension:
def list2dict(aList): """Returns a dictionary of the given list elements, with the list indices as keys.""" return dict([(i,aList[i]) for i in range(len(aList))])
-
An even slicker version, using
enumerate
:def list2dict(aList): """Returns a dictionary of the given list elements, with the list indices as keys.""" return dict(enumerate(aList))
You can remove a key/value pair from a dictionary, too. You'll need that on your assignment.
-
del aDict["silly"]
To see what is in a dictionary, it depends on whether you are looking for the keys or the values.
-
Looking for a key:
4 in aDict
-
Looking for a key:
"This ain't there." in aDict
-
Looking for a value:
24 in aDict.values()
-
Looking for a value:
"This ain't there." in aDict.values()
There are numerous other operations of lesser importance, as described in the Python documentation.
Looping over dictionaries
To access each of the dictionary elements, it is common to loop over the dictionary. This actually loops over the dictionary keys, from which you can get the values. Of course, dictionaries are not ordered, so you don't know which order in which you'll get the keys.
-
Just the keys:
for key in aDict: print key
-
Keys and values:
for key in aDict: print key, aDict[key]
Thus, looping on a dictionary is comparable to looping on a list's range.
However, there is a more “Pythonic” way to loop over both the key and value:
-
Keys and values, a better way:
for key,value in aDict.items(): print key, value
To understand this, observe thataDict.items()
returns a list of pairs.
How could you loop over just the values in a similar way? What function did we previously mention to get the values?
-
for value in aDict.values(): print value
Additional optional readings about Python dictionariess
- Python documentation: Dictionaries
- Python tutorial: Dictionaries
- Wikibooks: Python Dictionaries
- Google's Python class: Dictionaries and Files
- Dive Into Python: Dictionaries
- Python Course: Dictionaries