CSci 150: Foundations of computer science
Home Syllabus Readings Projects Tests

More with dictionaries

So far we've seen four operations relating to dictionary values:

{}Creates an empty dictionary
d[k] Retrieves/sets the value associated with key k
k in d Tests whether key k exists in dictionary d
d.keys() Returns a sequence of all keys in dictionary d

More operations

Now we'll examine a few more operations that are also useful.

Examples

First, recall that earlier we developed a program counting how many letters occur in a word typed by the user. The approach we saw before is listed at left below; the listing at right gives an alternative approach.

word = input()
counts = {}
for letter in word:
    if letter in counts:
        counts[letter] += 1
    else:
        counts[letter] = 1

for letter in sorted(counts.keys()):
    print('{0} {1:2d}'.format(lettercounts[letter]))
word = input()
counts = {}
for letter in word:
    old_count = counts.get(letter0)
    counts[letter] = old_count + 1

for letter in counts:  # Changed: unpredictable order!
    print('{0} {1:2d}'.format(lettercounts[letter]))

The if statement before is now replaced with the get method — something that cleans up the implementation considerably. The other change is in the for statement: It is also much shorter, but there is a key difference: Whereas the initial program would display the letters in alphabetical order, the second program displays the letters in an unpredictable order. If you wanted alphabetical order, you would want to use the initial version.

Or here's another example: Suppose we have a list sents of sentences, and we want to create an “index” mapping each word to the sentence containing that word.

index = {}
for s in sents:          # (iterate through each sentence,
    for w in s.split():  # and through each word in each sentence.)
        index[w] = s     # WARNING: a problem explained below

Note, though, that with each word is associated a sentence in which the word is found. But what if the word appears in multiple sentences? In this snippet, when we found the word in the second sentence, we'd overwrite the previous word/sentence pair with the new word/sentence pair, forgetting that there was another sentence.

To get around this, we'll change our dictionary to map words to lists of sentences containing the word.

index = {}
for s in sents:          # (iterate through each sentence,
    for w in s.split():  # and through each word in each sentence.)
        if w in index:
            index[w].append(s)   # already seen, append to list
        else:
            index[w] = [s]       # not seen before, create list with just s