Introduction to Computer Science
CompSci 101 : Spring 2014

Reasoning about Code

Think about the following pieces of code and diagnose them on paper rather than simply typing them into the interpreter.

Dictionaries

A dictionary is an unordered collection of values each with distinct keys. The key-value pair stored within the map is called an item.

Dictionaries might be used to associate student IDs with complete student records, words to their definitions (like a real dictionary), or states to the foods they are known for (click on the map for more details). What other examples of dictionaries can you think of?

Dictionaries in Python

In Python a dictionary associates any object with any other, like a list associates a number, or index, with the value it stores. For example, the code below

d = { 'a':1, 'b':2, 'c':3 }
print(len(d))
print(d)
will generate the output
3
{ 'a':1, 'b':2, 'c':3 }

Additionally items can be modified using the standard bracket operators for indexing, [],

d['a'] = d['b'] * 2
d['b'] += 1
d['z'] = 12
print(d)

will generate the output

{ 'a':4, 'b':3, 'c':3, 'z':12 }

Files of Words

Look at these blocks of code that use a dictionary to organize information about words in a file. The first was discussed in class. For the rest, explain both the type and purpose of the key and its associated value — what questions could you answer with the words organized in this way?