Python Dictionary Practice Questions for Beginners
Chapter 13 Recap and Practice
Your programs can now look things up by name. Here is the chapter in one table:
| You write | It does |
|---|---|
d = {"Sunny": 25, "Rocky": 30} | makes a dictionary of key-value pairs |
{} | an empty dictionary |
len(d) | counts the pairs |
d["Sunny"] | gives the value of a key; KeyError if the key is missing |
d.get("Lucky", 0) | gives the value, or the default when the key is missing |
"Lucky" in d | True if the key exists (checks keys, not values) |
d["Lucky"] = 22 | adds a new key, or changes the value of an old one |
d.update(other) | adds or replaces all the pairs of another dictionary |
d.pop("Rocky") | removes a pair and gives back its value |
del d["Rocky"] | removes a pair |
for key in d: | loops over the keys, in the order they were added |
for value in d.values(): | loops over the values |
for key, value in d.items(): | loops over the pairs, key and value together |
d[k] = d.get(k, 0) + 1 | counts things, one key per thing |
students[0]["name"] | reads nested data from the outside in |
And the checklist when a dictionary misbehaves: colons inside the pairs, commas between them, the exact spelling and capitals of every key, in or get() before reading a key that might be missing, and .items() when the loop has two variables.
Practice questions
Use input() with no prompt text. When a dictionary is printed, Python shows strings in single quotes, so your output will too. The tests try several inputs, so test your program with a few of your own, including a key that isn't there.
What is a dictionary
- 110.Python Program to Create a Dictionary from InputEasySolve
- 111.Fix the Broken Phone Book DictionaryMediumSolve
Reading values
- 112.Python Program to Look Up a Phone NumberEasySolve
- 113.Python Program to Calculate a Fruit BillMediumSolve
Adding, changing and deleting
- 114.Python Program to Add or Update a Mark in a DictionaryEasySolve
- 115.Python Program to Remove an Item from a Shopping CartMediumSolve
- 116.Python Program to Build a Price List from InputMediumSolve
Looping through a dictionary
- 117.Python Program to Print a Menu from a DictionaryEasySolve
- 118.Python Program to Count Each Letter in a WordMediumSolve
- 119.Python Program to Manage a Shop InventoryHardSolve
Now you can store data under names. Next, tuples and sets: two more ways to group values, one that never changes and one with no repeats.