Skip to content

Dictionary mutation, views, and comprehensions [ref]

Problem

  • Add "b": 2 to {"a": 1} and then delete "a".
  • Pop "a" from {"a": 1}; pop missing "x" with a default.
  • List the keys, values, and pairs of {"a": 1, "b": 2}.
  • Map values in [10, 20, 30] to their indices.
  • Remove zero-valued entries from {"a": 2, "b": 0}.

Python solution

d = {"a": 1}
d["b"] = 2
d  # {'a': 1, 'b': 2}
del d["a"]
d  # {'b': 2}

d = {"a": 1}
d.pop("a", None)  # 1
d.pop("x", None)  # None

d = {"a": 1, "b": 2}
list(d.keys())    # ['a', 'b']
list(d.values())  # [1, 2]
list(d.items())   # [('a', 1), ('b', 2)]

{value: i for i, value in enumerate([10, 20, 30])}
# {10: 0, 20: 1, 30: 2}

counts = {"a": 2, "b": 0}
{k: v for k, v in counts.items() if v}  # {'a': 2}