Chapter Review Questions

Chapter Review Questions#

Note

Source: Adapted from the C# edition (dictionaries/reviewdictionaries.rst). Questions updated for Python dict syntax and idioms.

  1. Is a Python dict mutable or immutable?

  2. What is the syntax to create a dictionary mapping "a" to 1 and "b" to 2?

  3. How do you iterate over all key-value pairs in a dictionary d?

  4. Two ways to look up a key.

    1. What does d[key] do if the key is not present?

    2. What does d.get(key, default) do instead?

    3. When would you prefer the second form?

  5. Comparing dicts and lists.

    1. How is a dictionary similar to a list?

    2. How is it different?

  6. Dictionary key restrictions.

    1. What restriction applies to dictionary keys?

    2. Why does that restriction exist?

  7. What does d.pop("x", None) do if "x" is not in d?

  8. Write one line that counts the number of entries in dictionary d.

  9. Given:

    counts = {}
    for word in ["a", "b", "a", "c", "a", "b"]:
        counts[word] = counts.get(word, 0) + 1
    

    What is counts after the loop?

  10. Why is looking up a key in a dictionary O(1) on average, while searching for a value in a list is O(N)?

  11. collections.Counter.

    1. What does collections.Counter add on top of a plain dict?

    2. Give an example use case.

  12. Keys and mutability.

    1. Can a list be used as a dictionary key? Why or why not?

    2. Can a tuple be used as a dictionary key? Why or why not?