Skip to content

Dictionary lookup and default values [ref]

Problem

  • Read "a" from {"a": 1} and read missing "b" as 0 without inserting it.
  • Increment "x" in an initially empty frequency dictionary.
  • Insert and return an empty dictionary for missing key "a" using setdefault.
  • Apply setdefault to existing key "a" in {"a": 3} without replacing 3.
  • Test whether "x" is a key in {"x": 1}.

Python solution

d = {"a": 1}
d["a"]       # 1
d.get("b", 0)  # 0
d            # {'a': 1}

counts = {}
counts["x"] = counts.get("x", 0) + 1
counts  # {'x': 1}

trie = {}
trie.setdefault("a", {})  # {}
trie  # {'a': {}}

d = {"a": 3}
d.setdefault("a", 99)  # 3
d  # {'a': 3}

"x" in {"x": 1}  # True