livepython.net
CHAPTER 13Dictionaries
13.5  PRACTICE

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 writeIt 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 dTrue if the key exists (checks keys, not values)
d["Lucky"] = 22adds 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) + 1counts 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

  1. 110.Python Program to Create a Dictionary from InputEasySolve
  2. 111.Fix the Broken Phone Book DictionaryMediumSolve

Reading values

  1. 112.Python Program to Look Up a Phone NumberEasySolve
  2. 113.Python Program to Calculate a Fruit BillMediumSolve

Adding, changing and deleting

  1. 114.Python Program to Add or Update a Mark in a DictionaryEasySolve
  2. 115.Python Program to Remove an Item from a Shopping CartMediumSolve
  3. 116.Python Program to Build a Price List from InputMediumSolve

Looping through a dictionary

  1. 117.Python Program to Print a Menu from a DictionaryEasySolve
  2. 118.Python Program to Count Each Letter in a WordMediumSolve
  3. 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.