A dictionary is a structure in Python for representing a one-way mapping between what we call a key to what we call a value.
For instance, we can create a simple dictionary as follows in Python.
>>> grades = { 'Alice': 97, 'Bob': 85, 'Carrie': 83 }
You can think of this as creating a table, in this case mapping names to test scores.
Alice → 97 Bob → 85 Carrie → 83
In this case, we're using strings as our keys and integers as our values, but Python is very flexible in what can be used for keys and values: We could, for example, have a dictionary mapping points to strings.
You can retrieve a value associated with a key by referencing
the dictionary followed by brackets containing the key value.
You can also use len to find how many key-value pairs
are in the dictionary, the in operator to test whether a
key is in the dictionary, and a for loop to
iterate through each key in the dictionary.
>>> print grades['Alice']
97
>>> print len(grades)
3
>>> print 'Quincy' in grades
False
>>> for name in grades:
>>> print name, 'got', grades[name]
Alice got 97
Carrie got 83
Bob got 85
Python doesn't maintain any ordering
to the keys, so the for loop could easily go through the keys
in a peculiar order.
You can modify the value associated with a key or add a new key-value mapping by assigning something into the dictionary.
>>> grades['Bob'] = 89
>>> grades['Dylan'] = 71
>>> print len(grades)
4
Each key in a dictionary maps to only one value. So when we
assign to grades['Bob'], Python notices that 'Bob'
already had a value associated with it, and it replaces that
association with a new one. When we assign
to grades['Dylan'], a new association is added into the
dictionary since 'Dylan' wasn't previously associated
with a value.
Here is a much more complex example involving a dictionary.
It finds which words occur most frequently in a file.
The dictionary counts is used to maintain the mapping from each
word to the number of times it has been found.
counts = {} # We start with an empty mapping
essay = open('essay.txt')
for line in essay:
for word in line.split():
if word not in counts: # This is the first time we have seen word,
counts[word] = 1 # so we save that we have seen it once
else:
counts[word] += 1 # Otherwise increment the count for word
max_count = 0 # max_count will be the largest count found
max_words = [] # max_words is list of words appearing max_count times
for word in counts:
count = counts[word]
if count > max_count: # This word beats out all previous ones
max_words = [word]
max_count = count
elif count == max_count: # This word ties the previous best
max_words.append(word)
print max_count, 'times:', ' '.join(max_words)