Skip to content

`defaultdict` and `OrderedDict` [ref]

Problem

  • Append "ant" under "a" in an empty defaultdict(list).
  • Access missing "x" in a defaultdict(list) and observe the insertion.
  • Move "a" to the most-recent end of an OrderedDict containing "a" then "b".
  • Remove the least-recent entry from that ordered dictionary.

Python solution

from collections import defaultdict, OrderedDict

groups = defaultdict(list)
groups["a"].append("ant")
dict(groups)  # {'a': ['ant']}

groups = defaultdict(list)
groups["x"]  # []
dict(groups)  # {'x': []}

cache = OrderedDict([("a", 1), ("b", 2)])
cache.move_to_end("a")
list(cache.items())  # [('b', 2), ('a', 1)]

cache.popitem(last=False)  # ('b', 2)
list(cache.items())        # [('a', 1)]