Coding Exercises · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. What does this print?
d = {'b': 2, 'c': 1, 'a': 3}
print(dict(sorted(d.items())))
2. What does this print?
d = {'x': 2, 'y': 1, 'z': 2, 'w': 1}
print(list(dict(sorted(d.items(), key=lambda i: i[1], reverse=True))))
3. What does this print?
d1 = {'a': 1, 'b': 2}
d2 = {'b': 3, 'c': 4}
print(d1.keys() & d2.keys(), type(d1.keys() & d2.keys()).__name__)
4. What does this print?
totals = {'go': 4}
for d in ({'go': 1, 'c': 2}, {'c': 5}):
    totals |= d
print(totals)
5. What does this print?
a = {'x': 1, 'y': 1, 'z': 1}
b = {'x': 1, 'y': 1}
c = {'x': 1}
print(sorted(a.keys() ^ b.keys() ^ c.keys()))
6. What does this print?
n1 = {'a': 0, 'b': 5}
n2 = {'b': 7}
print({k: n1.get(k) or -1 for k in n1.keys() - n2.keys()})
7. Which function signature lets merge accept any number of dictionaries, like merge(d1), merge(d1, d2, d3) or merge()?

Coding exercises

Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.

Exercise 1: Exercise 1: sort a dictionary by value

Write sort_dict_by_value(d) that returns a new dictionary with the same items as d, ordered by value from smallest to largest. Items with equal values keep their original relative order. Don't modify d.

Example: sort_dict_by_value({'Johann': 65, 'Ludwig': 56, 'Frederic': 39, 'Wolfgang': 35}) returns {'Wolfgang': 35, 'Frederic': 39, 'Ludwig': 56, 'Johann': 65}.

Hints (3)
  1. sorted(d.items(), key=...) returns a list of (key, value) tuples in the order you choose.
  2. Use key=lambda item: item[1] to sort by value.
  3. dict() accepts a list of pairs and keeps their order.
Show a solution
def sort_dict_by_value(d):
    return dict(sorted(d.items(), key=lambda item: item[1]))

Exercise 2: Exercise 2: common keys

Write intersect(d1, d2) that returns a dictionary containing only the keys present in both dicts. Each value is a tuple (d1[key], d2[key]). Key order doesn't matter.

Example: intersect({'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'b': 20, 'c': 30, 'y': 40, 'z': 50}) returns {'b': (2, 20), 'c': (3, 30)}.

Hints (2)
  1. d1.keys() & d2.keys() gives the set of shared keys.
  2. Build the result with a comprehension: {k: (d1[k], d2[k]) for k in ...}.
Show a solution
def intersect(d1, d2):
    return {k: (d1[k], d2[k]) for k in d1.keys() & d2.keys()}

Exercise 3: Exercise 3: merge word counts

Write merge(*dicts) that takes any number of word-frequency dicts and returns a single dict with the summed frequency of every word, ordered by frequency from highest to lowest. Words with equal totals keep the order in which they were first seen. Don't modify the inputs.

Example: with d1 = {'python': 10, 'java': 3, 'c#': 8, 'javascript': 15} and d2 = {'java': 10, 'c++': 10, 'c#': 4, 'go': 9, 'python': 6}, merge(d1, d2) returns {'python': 16, 'javascript': 15, 'java': 13, 'c#': 12, 'c++': 10, 'go': 9}.

Hints (3)
  1. update replaces values. You need to add each count to a running total: totals.get(word, 0) + count.
  2. Loop over every dict, and over every item in each dict.
  3. Finish with dict(sorted(totals.items(), key=..., reverse=True)). The sort is stable, so ties stay in first-seen order.
Show a solution
def merge(*dicts):
    totals = {}
    for d in dicts:
        for word, count in d.items():
            totals[word] = totals.get(word, 0) + count
    return dict(sorted(totals.items(), key=lambda item: item[1], reverse=True))

Exercise 4: Exercise 4: unevenly balanced requests

Write identify(node1, node2, node3) that takes three dicts mapping resources to request counts and returns a dict of the resources that appear on some, but not all, of the nodes.

Each value is a tuple of the three counts in node order, using 0 for a node where the resource is missing. Key order doesn't matter.

Example: with n1 = {'employees': 100, 'employee': 5000, 'users': 10, 'user': 100}, n2 = {'employees': 250, 'users': 23, 'user': 230} and n3 = {'employees': 150, 'users': 4, 'login': 1000}, the result is {'employee': (5000, 0, 0), 'user': (100, 230, 0), 'login': (0, 0, 1000)}.

Hints (3)
  1. Keys on at least one node: the union |. Keys on every node: the intersection &.
  2. The resources you want are union - intersection. (Chained ^ is not the same for three sets.)
  3. node.get(key, 0) returns 0 when the resource is missing.
Show a solution
def identify(node1, node2, node3):
    union = node1.keys() | node2.keys() | node3.keys()
    intersection = node1.keys() & node2.keys() & node3.keys()
    return {key: (node1.get(key, 0), node2.get(key, 0), node3.get(key, 0))
            for key in union - intersection}