Dictionaries
Python dictionaries are a data structure that contains key-item pairs. The keys must be immutable types, usually strings or tuples. Here is an example that shows how to construct a dictionary:
grades = {'Pete':87, 'Annie':92, 'Jodi':78}
To access an item, we provide the key as an index as follows:
print grades['Annie']
Dictionaries are mutable, so we can change the item values using them. If Jodi does extra work to improve her grade, we can change it as follows:
grades['Jodi'] += 10 print grades['Jodi']
To add an entry to a dictionary, just assign a value to a new key:
grades['Ivan']=94
However, attempting to access a nonexistent key yields an error.
An important point to realize is that dictionaries are not ordered. The following code is a standard idiom to iterate over a dictionary:
for key, item in grades.iteritems(): print "{:s}'s grade in the test is {:d}".format(key, item)
The main point...