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.
- The key is a distinct immutable object that represents the item as a whole.
- The value is any object.
Dictionaries might be used to associate student IDs with complete student records, or words to their definitions (like a real dictionary). What other examples of maps can you think of?
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?
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), 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 }