The compound types you have learned about strings, lists, and tuples use integers as indices. If you try to use any other type as an index, you get an error.
Dictionaries are similar to other compound types except that they can use any immutable type as an index. As an example, we will create a dictionary to translate English words into Spanish. For this dictionary, the indices are strings.
One way to create a dictionary is to start with the empty dictionary and add elements. The empty dictionary is denoted {}:
>>> eng2sp = {}
>>> eng2sp['one'] = 'uno'
>>> eng2sp['two'] = 'dos'
The first assignment creates a dictionary named eng2sp; the other assignments add new elements to the dictionary. We can print the current value of the dictionary in the usual way:
>>> print eng2sp
{'one': 'uno', 'two': 'dos'}
The elements of a dictionary appear in a comma-separated list. Each entry contains an index and a value separated by a colon. In a dictionary, the indices are called keys, so the elements are called key-value pairs.
Another way to create a dictionary is to provide a list of key-value pairs using the same syntax as the previous output:
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
If we print the value of eng2sp again, we get a surprise:
>>> print eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
The key-value pairs are not in order! Fortunately, there is no reason to care about the order, since the elements of a dictionary are never indexed with integer indices. Instead, we use the keys to look up the corresponding values:
>>> print eng2sp['two']
'dos'
The key 'two' yields the value 'dos' even though it appears in the third key-value pair.
10.1 Dictionary operations
The next two sections provide an introduction to dictionary operations and methods. A short reference for commonly used operators and methods can be found here and also in the left side of this page. A more complete list and explanations can be found
The del statement removes a key-value pair from a dictionary. For example, the following dictionary contains the names of various fruits and the number of each fruit in stock:
>>> inventory = {'apples': 430, 'bananas': 312,
'oranges': 525, 'pears': 217}
>>> print inventory
{'oranges': 525, 'apples': 430, 'pears': 217, 'bananas': 312}
If someone buys all of the pears, we can remove the entry from the dictionary:
>>> del inventory['pears']
>>> print inventory
{'oranges': 525, 'apples': 430, 'bananas': 312}
Or if we're expecting more pears soon, we might just change the value associated with pears:
>>> inventory['pears'] = 0
>>> print inventory
{'oranges': 525, 'apples': 430, 'pears': 0, 'bananas': 312}
The len function also works on dictionaries; it returns the number of key-value pairs:
>>> len(inventory)
4
10.2 Dictionary methods
A method is similar to a function it takes arguments and returns a value but the syntax is different. For example, the keys method takes a dictionary and returns a list of the keys that appear, but instead of the function syntax keys(eng2sp), we use the method syntax eng2sp.keys().
>>> eng2sp.keys()
['one', 'three', 'two']
This form of dot notation specifies the name of the function, keys, and the name of the object to apply the function to, eng2sp. The parentheses indicate that this method has no parameters.
A method call is called an invocation; in this case, we would say that we are invoking keys on the object eng2sp.
The values method is similar; it returns a list of the values in the dictionary:
>>> eng2sp.values()
['uno', 'tres', 'dos']
The items method returns both, in the form of a list of tuples one for each key-value pair:
>>> eng2sp.items()
[('one','uno'), ('three', 'tres'), ('two', 'dos')]
The syntax provides useful type information. The square brackets indicate that this is a list. The parentheses indicate that the elements of the list are tuples.
If a method takes an argument, it uses the same syntax as a function call. For example, the method has_key takes a key and returns true (1) if the key appears in the dictionary:
>>> eng2sp.has_key('one')
True
>>> eng2sp.has_key('deux')
False
If you try to call a method without specifying an object, you get an error. In this case, the error message is not very helpful:
>>> has_key('one')
NameError: has_key
10.3 Aliasing and copying
Because dictionaries are mutable, you need to be aware of aliasing. Whenever two variables refer to the same object, changes to one affect the other.
If you want to modify a dictionary and keep a copy of the original, use the copy method. For example, opposites is a dictionary that contains pairs of opposites:
>>> opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'}
>>> alias = opposites
>>> copy = opposites.copy()
alias and opposites refer to the same object; copy refers to a fresh copy of the same dictionary. If we modify alias, opposites is also changed:
>>> alias['right'] = 'left'
>>> opposites['right']
'left'
If we modify copy, opposites is unchanged:
>>> copy['right'] = 'privilege'
>>> opposites['right']
'left'
10.4 Looping Techniques
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
10.4 Counting letters
In Chapter 7, we wrote a function that counted the number of occurrences of a letter in a string. A more general version of this problem is to form a histogram of the letters in the string, that is, how many times each letter appears.
Such a histogram might be useful for compressing a text file. Because different letters appear with different frequencies, we can compress a file by using shorter codes for common letters and longer codes for letters that appear less frequently.
Dictionaries provide an elegant way to generate a histogram:
>>> letterCounts = {}
>>> for letter in "Mississippi":
... letterCounts[letter] = letterCounts.get (letter, 0) + 1
...
>>> letterCounts
{'M': 1, 's': 4, 'p': 2, 'i': 4}
We start with an empty dictionary. For each letter in the string, we find the current count (possibly zero) and increment it. At the end, the dictionary contains pairs of letters and their frequencies.
It might be more appealing to display the histogram in alphabetical order. We can do that with the items and sort methods:
>>> letterItems = letterCounts.items()
>>> letterItems.sort()
>>> print letterItems
[('M', 1), ('i', 4), ('p', 2), ('s', 4)]
You have seen the items method before, but sort is the first method you have encountered that applies to lists. There are several other list methods, including append, extend, and reverse. Consult the Python documentation for details.
10.8 Glossary
dictionary
A collection of key-value pairs that maps from keys to values. The keys can be any
immutable type, and the values can be any type.
key
A value that is used to look up an entry in a dictionary.
key-value pair
One of the items in a dictionary.
method
A kind of function that is called with a different syntax and invoked "on" an object.
invoke
To call a method.
hint
Temporary storage of a precomputed value to avoid redundant computation.
overflow
A numerical result that is too large to be represented in a numerical format.