Dictionary Methods · Exercises
Beginner

Dictionary Methods Exercises

4 exercises that build on the Python Dictionary Methods lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: Dictionary methods are the built-in tools for everyday dictionary jobs: reading with a fallback, creating entries on first use, removing and merging pairs, viewing keys and values, and building new dictionaries. By the end you can read, add, remove, merge and copy dictionary entries without a KeyError, use the live key, value and item views, build dictionaries with zip, fromkeys and comprehensions, and sort a dictionary by value. You will practise: Settings with defaults; Predict the dictionary methods; Fix the stock counter; Build a word index.

0 / 4 completed

Dictionary Methods practice exercises

1. Settings with defaults

Write code Easy

Complete with_defaults(settings, defaults). It must return a new dictionary that contains every default, with the user's settings overriding any default that has the same key. Neither argument may be changed.

Your code
def with_defaults(settings, defaults):
    # return a NEW dict: all defaults, overridden by settings
    pass

print(with_defaults({"theme": "dark"}, {"theme": "light", "font": 14}))

2. Predict the dictionary methods

Predict the output Easy

Read the code and type exactly what it prints, line by line. Then press Check to run it and compare.

Read this code
tally = {"a": 1}
print(tally.setdefault("a", 10))
print(tally.setdefault("b", 20))
print(tally.get("c", 30))
print(tally)
print(tally.pop("b"))
print(tally.popitem())
print(tally)

3. Fix the stock counter

Fix the bug Medium

add_stock(stock, item, qty) should add qty to the item's count and create the item (starting from 0) when it is new. Adding to an existing item works, but a new item crashes the program with a TypeError. Fix the function.

Your code
def add_stock(stock, item, qty):
    # add qty to the item's count; a new item starts from 0
    stock[item] = stock.get(item) + qty

inventory = {"apples": 5}
add_stock(inventory, "apples", 3)
add_stock(inventory, "kiwis", 4)
print(inventory)

4. Build a word index

Write code Hard

Write word_index(lines). lines is a list of strings. Return a dictionary that maps every word, in lowercase, to the list of line numbers (starting at 1) on which it appears. A line number is listed once per word, even if the word repeats on that line, and the numbers are in increasing order. Words are separated by spaces. Empty lines still count as lines.

Your code
def word_index(lines):
    # map each lowercase word to the line numbers (from 1) where it appears
    pass

text = ["Red apple", "green apple and red pear", "Apple apple"]
print(word_index(text))

Next lessonPython Nested Data Structures

More Python Dictionary Methods examples · All Python exercises