11.3 Dictionary operations
From Foundations of Python ProgrammingGNU FDL 1.3Original pagePython1 class period1 exercise1 graded test
11.3 Dictionary operations
The del statement removes a key-value pair from a dictionary. For example, the following dictionary contains the
names of various fruits and the number of each fruit in stock. If someone buys all of the pears, we can remove the
entry from the dictionary.
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
del inventory['pears']
Step through this code in the book.
Dictionaries are mutable, as the delete operation above indicates. As we've seen before with lists, this means that the
dictionary can be modified by referencing an association on the left hand side of the assignment statement. In the
previous example, instead of deleting the entry for pears, we could have set the inventory to 0.
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
inventory['pears'] = 0
Step through this code in the book.
Note
Setting the value associated with
pearsto 0 has a different effect than removing the key-value pair entirely withdel. Try printout out the two dictionaries in the examples above.
Similarily, a new shipment of 200 bananas arriving could be handled like this. Notice that there are now 512 bananas---
the dictionary has been modified. Note also that the len function also works on dictionaries. It returns the number
of key-value pairs.
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
inventory['bananas'] = inventory['bananas'] + 200
numItems = len(inventory)
Step through this code in the book.
Notice that there are now 512 bananas---the dictionary has been modified. Note also that the len function also
works on dictionaries. It returns the number of key-value pairs.
Check your understanding
Check your understanding: a multiple-choice question in the book.
Exercise 1
2. Update the value for "Phelps" in the dictionary swimmers to include his medals from the Rio Olympics by adding 5 to the current value (Phelps will now have 28 total medals). Do not rewrite the dictionary.
Open the
01folder and editmain.py. Run Tests checks it.
For teachers
11.3 Dictionary operations
Students read Foundations of Python Programming's “Dictionary operations” in CS Room and work through its 1 Python coding exercise (1 graded).
- Time: 1 class period
- Tests: 1 in 1 graded exercise, set up for you when you import the lesson
Exercises
| Folder | Grading | Tests |
|---|---|---|
01 | Autograded | 1 |