SyntaxPilot
Courses/Python Coding Questions/Lesson 16
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Python Coding Questions · Lesson 16 of 30

Dictionary questions

invert a dict (duplicate values)merge dicts (

These are the notes for Python Coding Questions, episode 16: dictionary questions. Three questions that show up in interviews and in real code every day: inverting a dictionary when values repeat, merging two dictionaries (including nested ones), and safely reading a value deep inside nested data with a path like "customer.address.city". Each one hides a trap that doesn't crash: a one-liner that silently loses data, an update() that changes the dictionary you started from, and a merge that throws away nested settings. Along the way you'll see TypeError: unhashable type: 'list', KeyError and AttributeError: 'str' object has no attribute 'get'.

Every program was run with Python 3.13 (python3 main.py), the SyntaxPilot compiler's Python command. Every output below is real. Tracebacks show the full path to your file; here it is shortened to main.py.

A quick reminder: a dictionary (dict) stores key → value pairs. You look a value up by its key: marks["Asha"]. Keys are unique (one key appears once), and since Python 3.7 a dictionary keeps the order in which keys were first added. Looking up a key takes O(1) time on average, because Python finds it by its hash (a number computed from the key).

Q1: Invert a dictionary (with duplicate values)

Real-life example: a teacher's mark sheet maps each student's name to their mark: Asha 90, Ravi 85, Neha 90, Kabir 72. The principal asks the other way round: who got 90? So we invert the dictionary: marks become keys, names become values. But two students can have the same mark, and 90 must give both Asha and Neha.

The question: given a dictionary, build its inverse: each value maps to all the keys that had it.

Input Output
{"Asha": 90, "Ravi": 85, "Neha": 90, "Kabir": 72} {90: ['Asha', 'Neha'], 85: ['Ravi'], 72: ['Kabir']}
{} {}
{"a": 1} {1: ['a']}

Ask the interviewer: can values repeat? (If they can't, the simple version is fine.) Should every value map to a list, even when only one key had it? Are the values hashable (can they be keys)?

Attempt 1: a dictionary comprehension that swaps each pair

A dictionary comprehension builds a dictionary in one line: {key_expr: value_expr for ... in ...}. marks.items() gives the (name, mark) pairs.

marks = {"Asha": 90, "Ravi": 85, "Neha": 90, "Kabir": 72}

by_mark = {mark: name for name, mark in marks.items()}
print(by_mark)
print(by_mark[90])

Output:

{90: 'Neha', 85: 'Ravi', 72: 'Kabir'}
Neha

90 maps to only Neha. Asha has disappeared, and there was no error.

Why it fails

Keys are unique. Asha's 90 went in first; then Neha's 90 used the same key and overwrote the value. The last one wins. Here's the same thing in slow motion:

d = {}
d[90] = "Asha"
print(d)
d[90] = "Neha"          # same key: the value is replaced
print(d, len(d))

Output:

{90: 'Asha'}
{90: 'Neha'} 1

A silent overwrite is the worst kind of bug: nothing tells you. One way to notice it: len(by_mark) is 3, but there were 4 students.

The fix: one key, a list of values

Many names can share one mark, so in the inverse, each value must be a list of names. The first time we see a mark, give it an empty list; then always append.

marks = {"Asha": 90, "Ravi": 85, "Neha": 90, "Kabir": 72}

by_mark = {}
for name, mark in marks.items():
    if mark not in by_mark:
        by_mark[mark] = []          # first student with this mark
    by_mark[mark].append(name)
print(by_mark)
print(by_mark[90], by_mark.get(100, []))

Output:

{90: ['Asha', 'Neha'], 85: ['Ravi'], 72: ['Kabir']}
['Asha', 'Neha'] []

Nobody is lost. by_mark.get(100, []) returns the default [] for a mark nobody got, instead of raising KeyError.

Three ways to write "start a list if it's missing"

dict.setdefault(key, default) returns the value for key, first inserting default if the key is missing. collections.defaultdict(list) is a dictionary that creates a missing key's value by calling list() (an empty list) the moment you ask for it.

from collections import defaultdict

marks = {"Asha": 90, "Ravi": 85, "Neha": 90, "Kabir": 72}

a = {}
for name, mark in marks.items():
    a.setdefault(mark, []).append(name)

b = defaultdict(list)          # a missing key starts as []
for name, mark in marks.items():
    b[mark].append(name)

print(a)
print(b)
print(dict(b) == a)

Output:

{90: ['Asha', 'Neha'], 85: ['Ravi'], 72: ['Kabir']}
defaultdict(<class 'list'>, {90: ['Asha', 'Neha'], 85: ['Ravi'], 72: ['Kabir']})
True

print(b) shows defaultdict(<class 'list'>, {...}); dict(b) turns it into a plain dictionary. One thing to know about defaultdict: just reading a missing key creates it.

from collections import defaultdict

b = defaultdict(list)
print(b["nobody"])
print(dict(b))         # reading the key added it
print("x" in b)        # 'in' does NOT add it

Output:

[]
{'nobody': []}
False

So use in or .get() to check a defaultdict without adding keys.

Trap: a list can't be a key

What if the values are lists themselves? Each student has a list of clubs:

from collections import defaultdict

marks = {"Asha": 90, "Ravi": 85, "Neha": 90, "Kabir": 72}
by_mark = defaultdict(list)          # a missing key starts as []
for name, mark in marks.items():
    by_mark[mark].append(name)
print(dict(by_mark))

clubs = {"Asha": ["chess", "music"], "Ravi": ["chess"]}
print({v: k for k, v in clubs.items()})

Output:

{90: ['Asha', 'Neha'], 85: ['Ravi'], 72: ['Kabir']}
Traceback (most recent call last):
  File "main.py", line 10, in <module>
    print({v: k for k, v in clubs.items()})
           ^^^^
TypeError: unhashable type: 'list'

Why? A dictionary finds a key by its hash. A list is mutable: it can change, and then its hash would change and the dictionary couldn't find it any more. So Python refuses: lists are unhashable. Keys must be hashable: immutable values like strings, numbers, tuples (of hashable things) and frozensets.

print(hash("chess"), hash(90) == hash(90))
print(hash(("chess", "music")) == hash(("chess", "music")))
print({("chess", "music"): "Asha"})
print(hash(["chess"]))

Output:

-1404062702410650534 True
True
{('chess', 'music'): 'Asha'}
Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(hash(["chess"]))
          ~~~~^^^^^^^^^^^
TypeError: unhashable type: 'list'

(String hashes are randomised each time Python starts, so the first number changes from run to run.)

What we usually want is "each club, with its members": one entry per item in the list.

from collections import defaultdict

clubs = {"Asha": ["chess", "music"], "Ravi": ["chess"]}
members = defaultdict(list)
for name, club_list in clubs.items():
    for club in club_list:           # one entry per club
        members[club].append(name)
print(dict(members))

Output:

{'chess': ['Asha', 'Ravi'], 'music': ['Asha']}

Complexity: O(n) time (one step per pair, or per list item), O(n) space for the new dictionary.

When values are unique (like a code → name table), the one-liner is exactly right, and you can even check that it was safe:

codes = {"IN": "India", "JP": "Japan", "BR": "Brazil"}
names = {v: k for k, v in codes.items()}
print(names)
print(len(names) == len(codes))      # True: no value was repeated

Output:

{'India': 'IN', 'Japan': 'JP', 'Brazil': 'BR'}
True

Q2: Merge two dictionaries

Real-life example: every app has default settings: light theme, font size 14, sound on. You only change what you care about: you pick the dark theme. What you see is both together, with your choice winning wherever they overlap. And the defaults must stay the same for the next user.

The question: merge defaults and user into one dictionary where user wins, without changing either input. Then: what if the settings are nested (a dictionary inside a dictionary)?

Attempt 1: settings = defaults, then update

d.update(other) copies every key of other into d, overwriting keys that are already there.

defaults = {"theme": "light", "font": 14, "sound": True}
user = {"theme": "dark"}

settings = defaults
settings.update(user)
print(settings)
print(defaults)

Output:

{'theme': 'dark', 'font': 14, 'sound': True}
{'theme': 'dark', 'font': 14, 'sound': True}

settings is right, but defaults changed too. The next user would get your dark theme.

Why: = gives a second name, not a copy

settings = defaults doesn't copy anything. It gives the same dictionary a second name. update changes a dictionary in place. Two names, one dictionary:

defaults = {"theme": "light"}
settings = defaults
print(settings is defaults)
copy = dict(defaults)            # or defaults.copy()
print(copy is defaults, copy == defaults)

Output:

True
False True

is checks whether two names point to the same object; == checks whether two objects have equal contents.

The fix: build a new dictionary

Three ways that leave both inputs alone:

defaults = {"theme": "light", "font": 14, "sound": True}
user = {"theme": "dark"}

print({**defaults, **user})
print(defaults | user)               # Python 3.9+
print(user | defaults)               # order matters: right side wins
print(defaults)                      # unchanged

Output:

{'theme': 'dark', 'font': 14, 'sound': True}
{'theme': 'dark', 'font': 14, 'sound': True}
{'theme': 'light', 'font': 14, 'sound': True}
{'theme': 'light', 'font': 14, 'sound': True}
  • {**a, **b}: ** unpacks a dictionary's pairs into a new dictionary literal. Later pairs overwrite earlier ones, so b wins.
  • a | b: the union operator for dictionaries (Python 3.9 and later). Same result: a new dictionary, the right side wins.
  • user | defaults: swap the order, and the defaults win. Order matters.
  • a |= b is the in-place version: it's the same as a.update(b). Use it only when you mean to change a.

You can also start from a copy and update the copy:

defaults = {"theme": "light", "font": 14, "sound": True}
user = {"theme": "dark"}
settings = defaults.copy()
settings.update(user)
print(settings, defaults)

Output:

{'theme': 'dark', 'font': 14, 'sound': True} {'theme': 'light', 'font': 14, 'sound': True}

The nested trap: | is a shallow merge

Real settings are nested: the app part is itself a dictionary.

defaults = {"app": {"theme": "light", "font": 14}, "sound": True}
user = {"app": {"font": 18}}

print(defaults | user)

Output:

{'app': {'font': 18}, 'sound': True}

The theme is gone. Why? | (and ** and update) is a shallow merge: it only looks at the top-level keys. Both have the key app, so the user's whole inner dictionary replaces the default one. It never looks inside.

The fix: a deep merge (recursion)

A deep merge goes inside. For each key in b: if the value is a dictionary on both sides, merge those two the same way; otherwise b's value wins. Each level is the same problem, one level smaller, so the function calls itself: that's recursion. isinstance(x, dict) checks whether x is a dictionary.

def deep_merge(a, b):
    result = dict(a)                       # a copy: a stays as it is
    for key, value in b.items():
        if (key in result and isinstance(result[key], dict)
                and isinstance(value, dict)):
            result[key] = deep_merge(result[key], value)   # both dicts: go in
        else:
            result[key] = value            # otherwise b wins
    return result

defaults = {"app": {"theme": "light", "font": 14}, "sound": True}
user = {"app": {"font": 18}, "lang": "en"}
print(deep_merge(defaults, user))
print(defaults)
print(deep_merge({"a": {"b": 1}}, {"a": 5}))

Output:

{'app': {'theme': 'light', 'font': 18}, 'sound': True, 'lang': 'en'}
{'app': {'theme': 'light', 'font': 14}, 'sound': True}
{'a': 5}

theme is kept, font is 18, sound is kept and lang is added. defaults is unchanged. When b has a plain value where a has a dictionary, b wins.

A subtle point: shared inner dictionaries. dict(a) is a shallow copy: the new outer dictionary holds the same inner dictionaries as a. Inner dictionaries that b doesn't touch are shared, so changing them later through the result also changes a:

import copy

def deep_merge(a, b):
    result = dict(a)
    for key, value in b.items():
        if (key in result and isinstance(result[key], dict)
                and isinstance(value, dict)):
            result[key] = deep_merge(result[key], value)
        else:
            result[key] = value
    return result

defaults = {"app": {"theme": "light"}, "audio": {"volume": 5}}
merged = deep_merge(defaults, {"app": {"theme": "dark"}})
merged["audio"]["volume"] = 10                 # audio was never merged: shared!
print(defaults["audio"])

defaults = {"app": {"theme": "light"}, "audio": {"volume": 5}}
merged = deep_merge(copy.deepcopy(defaults), {"app": {"theme": "dark"}})
merged["audio"]["volume"] = 10
print(defaults["audio"])

Output:

{'volume': 10}
{'volume': 5}

copy.deepcopy(x) copies x and everything inside it, at every level. Use it when the result must be completely independent.

Complexity: the shallow merge is O(len(a) + len(b)). The deep merge copies each level of a it walks through and visits every key of b at every level: O(size of a + size of b) in the worst case.

Q3: Get a nested value by a path

Real-life example: a food delivery app gets each order as nested data, the way JSON (the text format web APIs use) looks once Python loads it: dictionaries and lists inside each other. The rider needs the city: order["customer"]["address"]["city"], three levels down. The app stores where to look as one path string, "customer.address.city". And real data has gaps: some customers never gave a phone number.

The question: write get_path(data, path, default=None) that follows a dotted path and returns the value, or default if any part of the path isn't there. It must never crash.

Path Result
"customer.address.city" 'Pune'
"customer.name" 'Asha'
"customer.phone" None (missing)
"customer.name.first" None (name is a string, not a dict)
"id.x" None (id is a number)

Attempt 1: the whole path as one key

order = {
    "id": 501,
    "customer": {"name": "Asha",
                 "address": {"city": "Pune", "pin": "411001"}},
    "items": ["chai", "samosa"],
}

print(order["customer"]["address"]["city"])
print(order["customer.address.city"])

Output:

Pune
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print(order["customer.address.city"])
          ~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'customer.address.city'

Three square brackets work, but the dictionary has no key with dots in it. The path is three keys.

Attempt 2: split the path, step one level per key

path.split(".") turns "customer.address.city" into ['customer', 'address', 'city']. Then step one level down for each key.

order = {
    "id": 501,
    "customer": {"name": "Asha",
                 "address": {"city": "Pune", "pin": "411001"}},
    "items": ["chai", "samosa"],
}

def get_path(data, path):
    for key in path.split("."):        # "a.b.c" -> ["a", "b", "c"]
        data = data[key]               # one level down
    return data

print(get_path(order, "customer.address.city"))
print(get_path(order, "customer.name"))
print(get_path(order, "customer.phone"))

Output:

Pune
Asha
Traceback (most recent call last):
  File "main.py", line 15, in <module>
    print(get_path(order, "customer.phone"))
          ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
  File "main.py", line 10, in get_path
    data = data[key]               # one level down
           ~~~~^^^^^
KeyError: 'phone'

Square brackets raise KeyError on a missing key.

Attempt 3: .get() at every level

d.get(key, default) returns default instead of raising KeyError.

order = {
    "id": 501,
    "customer": {"name": "Asha",
                 "address": {"city": "Pune", "pin": "411001"}},
    "items": ["chai", "samosa"],
}

def get_path(data, path, default=None):
    for key in path.split("."):
        data = data.get(key, default)
    return data

print(get_path(order, "customer.phone"))
print(get_path(order, "customer.name.first"))

Output:

None
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    print(get_path(order, "customer.name.first"))
          ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "main.py", line 10, in get_path
    data = data.get(key, default)
           ^^^^^^^^
AttributeError: 'str' object has no attribute 'get'

The missing phone gives None. But "customer.name.first" crashes with AttributeError. Why? name is the string "Asha", not a dictionary, and a string has no .get method. .get only fixes missing keys; it doesn't check that we're still inside a dictionary. (There's a second hidden bug: "customer.phone.x" would call .get on None and crash with AttributeError: 'NoneType' object has no attribute 'get'.)

The fix: check every level before stepping

Before every step, check two things: is the current value a dictionary (isinstance(data, dict)), and is the key in it? If either fails, the path doesn't exist: return the default straight away.

order = {
    "id": 501,
    "customer": {"name": "Asha",
                 "address": {"city": "Pune", "pin": "411001"}},
    "items": ["chai", "samosa"],
}

def get_path(data, path, default=None):
    for key in path.split("."):
        if not isinstance(data, dict) or key not in data:
            return default             # missing, or not a dict here
        data = data[key]
    return data

tests = ["customer.address.city", "customer.name", "customer.phone",
         "customer.name.first", "items", "id.x", "nothing.at.all"]
for path in tests:
    print(path, "->", get_path(order, path))
print(get_path(order, "customer.phone", "not given"))

Output:

customer.address.city -> Pune
customer.name -> Asha
customer.phone -> None
customer.name.first -> None
items -> ['chai', 'samosa']
id.x -> None
nothing.at.all -> None
not given

Every path, no crash. or short-circuits: if data isn't a dictionary, Python never evaluates key not in data.

Why key not in data and not data.get(key) is None? Because a key can exist with the value None (or 0, or ""). in tells "missing" apart from "present but empty".

Another way: EAFP. Python programmers often "try it and handle the failure" (EAFP: easier to ask forgiveness than permission) instead of "check first" (LBYL: look before you leap):

order = {
    "id": 501,
    "customer": {"name": "Asha",
                 "address": {"city": "Pune", "pin": "411001"}},
    "items": ["chai", "samosa"],
}

def get_path(data, path, default=None):
    try:
        for key in path.split("."):
            data = data[key]
        return data
    except (KeyError, TypeError):
        return default

for path in ["customer.address.city", "customer.phone", "customer.name.first", "id.x", "items.0"]:
    print(path, "->", get_path(order, path))

Output:

customer.address.city -> Pune
customer.phone -> None
customer.name.first -> None
id.x -> None
items.0 -> None

"Asha"["first"] raises TypeError (a string index must be a number), and 501["x"] raises TypeError too, so both are caught. Careful: "items.0" gives None because "0" is a string and lists need an integer index. The practice questions below add list support.

Complexity: O(k) time for a path of k keys (each lookup is O(1) on average), O(k) space for the list from split.

Common mistakes (and what you really see)

Mistake What you see Why Fix
{v: k for k, v in d.items()} with repeated values {90: 'Neha', ...}: Asha is lost keys are unique: the last one wins a list per key, defaultdict(list)
a list as a key TypeError: unhashable type: 'list' keys must not be able to change one key per item, or a tuple
reading a missing key of a defaultdict to check it the key appears, with [] reading creates it key in d or d.get(key)
settings = defaults; settings.update(user) defaults changed too = is a second name, not a copy defaults | user or defaults.copy()
user | defaults your choices are ignored the right side wins defaults | user
a | b with nested dicts "theme" is lost shallow: the inner dict is replaced a recursive deep_merge
a deep merge built on dict(a) changing the result changes a untouched inner dicts are shared copy.deepcopy first
data["a.b.c"] KeyError: 'a.b.c' no key has dots in it path.split(".")
data[key] at each level KeyError: 'phone' a missing key key in data first
data.get(key) at each level AttributeError: 'str' object has no attribute 'get' not a dict any more isinstance(data, dict)
data.get(key) is None to mean "missing" a real None value looks missing a key can hold None key not in data

Your turn: flatten a dictionary (solution)

The opposite of get_path: turn a nested dictionary into one level, where each leaf value's key is its full path joined with dots. {"a": {"b": 1, "c": {"d": 2}}, "e": 3} → {"a.b": 1, "a.c.d": 2, "e": 3}. Hint: recursion, carrying the path so far.

Solution

Walk the dictionary. For each key, build the full path (prefix + "." + key, or just key at the top). If the value is a non-empty dictionary, recurse into it with that path; otherwise it's a leaf: store it.

def flatten(d, prefix=""):
    out = {}
    for key, value in d.items():
        path = f"{prefix}.{key}" if prefix else key
        if isinstance(value, dict) and value:
            out.update(flatten(value, path))   # go one level down
        else:
            out[path] = value                  # a leaf
    return out

print(flatten({"a": {"b": 1, "c": {"d": 2}}, "e": 3}))
order = {"id": 501, "customer": {"name": "Asha", "address": {"city": "Pune", "pin": "411001"}}}
for path, value in flatten(order).items():
    print(path, "=", value)
print(flatten({}), flatten({"a": {}}))

Output:

{'a.b': 1, 'a.c.d': 2, 'e': 3}
id = 501
customer.name = Asha
customer.address.city = Pune
customer.address.pin = 411001
{} {'a': {}}

An empty inner dictionary is kept as a leaf ({'a': {}}), so no information is lost. And every flattened path works with get_path. O(n) time for n keys in total (plus building the path strings).

Practice questions (with solutions)

1. Group words by their first letter. ["chai", "coffee", "dosa", "chutney", "idli"] → {'c': ['chai', 'coffee', 'chutney'], 'd': ['dosa'], 'i': ['idli']}.

Solution

The same pattern as inverting: a list per key, with defaultdict(list).

from collections import defaultdict

words = ["chai", "coffee", "dosa", "chutney", "idli"]
groups = defaultdict(list)
for w in words:
    groups[w[0]].append(w)
print(dict(groups))

Output:

{'c': ['chai', 'coffee', 'chutney'], 'd': ['dosa'], 'i': ['idli']}

2. Invert a dictionary, but raise an error if values repeat. For a code table that must be one-to-one.

Solution
def invert_unique(d):
    out = {}
    for k, v in d.items():
        if v in out:
            raise ValueError(f"value {v!r} is used by both {out[v]!r} and {k!r}")
        out[v] = k
    return out

print(invert_unique({"IN": "India", "JP": "Japan"}))
print(invert_unique({"Asha": 90, "Neha": 90}))

Output:

{'India': 'IN', 'Japan': 'JP'}
Traceback (most recent call last):
  File "main.py", line 10, in <module>
    print(invert_unique({"Asha": 90, "Neha": 90}))
          ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "main.py", line 5, in invert_unique
    raise ValueError(f"value {v!r} is used by both {out[v]!r} and {k!r}")
ValueError: value 90 is used by both 'Asha' and 'Neha'

raise ValueError(...) stops the function with a clear message instead of silently losing data.

3. Count with a dictionary, then merge two counts by adding. Two shops counted their sales; combine them.

Solution

| would replace the numbers; we want to add them. Loop with .get(key, 0), or use collections.Counter, whose + adds counts.

from collections import Counter

shop1 = {"chai": 30, "samosa": 12}
shop2 = {"chai": 25, "vada": 8}

total = dict(shop1)
for item, n in shop2.items():
    total[item] = total.get(item, 0) + n
print(total)
print(shop1 | shop2)                       # replaces: not what we want
print(dict(Counter(shop1) + Counter(shop2)))

Output:

{'chai': 55, 'samosa': 12, 'vada': 8}
{'chai': 25, 'samosa': 12, 'vada': 8}
{'chai': 55, 'samosa': 12, 'vada': 8}

4. Set a nested value by path, creating the levels. set_path(d, "a.b.c", 1) on {} gives {'a': {'b': {'c': 1}}}.

Solution

Walk all keys except the last, creating a dictionary at each missing level with setdefault; then assign the last key.

def set_path(data, path, value):
    *parents, last = path.split(".")
    for key in parents:
        data = data.setdefault(key, {})     # go down, creating if needed
    data[last] = value

config = {}
set_path(config, "db.host", "localhost")
set_path(config, "db.port", 5432)
set_path(config, "debug", True)
print(config)

Output:

{'db': {'host': 'localhost', 'port': 5432}, 'debug': True}

*parents, last = [...] is extended unpacking: last gets the last item, and parents a list of all the others.

5. get_path that also handles list indexes. "items.0" should give "chai".

Solution

When the current value is a list and the key is all digits, use it as an integer index (if it's in range).

order = {"id": 501, "customer": {"name": "Asha"}, "items": ["chai", "samosa"]}

def get_path(data, path, default=None):
    for key in path.split("."):
        if isinstance(data, dict) and key in data:
            data = data[key]
        elif isinstance(data, list) and key.isdigit() and int(key) < len(data):
            data = data[int(key)]
        else:
            return default
    return data

for path in ["items.0", "items.1", "items.5", "customer.name", "items.x"]:
    print(path, "->", get_path(order, path))

Output:

items.0 -> chai
items.1 -> samosa
items.5 -> None
customer.name -> Asha
items.x -> None

6. A deep merge that also joins lists. When both sides have a list, keep the items of both.

Solution

One more elif in the same recursive function.

def deep_merge(a, b):
    result = dict(a)
    for key, value in b.items():
        old = result.get(key)
        if isinstance(old, dict) and isinstance(value, dict):
            result[key] = deep_merge(old, value)
        elif isinstance(old, list) and isinstance(value, list):
            result[key] = old + value          # a new list with both
        else:
            result[key] = value
    return result

a = {"tags": ["python"], "app": {"plugins": ["git"], "font": 14}}
b = {"tags": ["interview"], "app": {"plugins": ["lint"]}}
print(deep_merge(a, b))

Output:

{'tags': ['python', 'interview'], 'app': {'plugins': ['git', 'lint'], 'font': 14}}

(Here result.get(key) is fine: a missing key gives None, which is neither a dict nor a list, so b's value is simply stored.)

Quick quiz

What does this print?

a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
c = a | b
c["x"] = 9
print(a["x"], c["y"], len(c))

(A) 9 3 3 (B) 1 2 4 (C) 1 3 3 (D) 1 3 4

Answer

(C). a | b builds a new dictionary, so changing c doesn't touch a: a["x"] is still 1. When a key is in both, the right side wins, so c["y"] is 3. The keys are x, y and z: len(c) is 3.

a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
c = a | b
c["x"] = 9
print(a["x"], c["y"], len(c))

Output:

1 3 3

Interview questions

  1. How do you invert a dictionary whose values can repeat? Map each value to a list of keys: defaultdict(list) and inv[v].append(k). The one-line comprehension keeps only the last key for each value.
  2. Why can't a list be a dictionary key? Keys are found by their hash; a list is mutable, so its hash could change and the key would be lost. Lists are unhashable; use a tuple.
  3. What's the difference between setdefault and defaultdict? d.setdefault(k, []) inserts the default for one call; defaultdict(list) creates a default for any missing key, even when you only read it.
  4. How do you merge two dictionaries without changing either? a | b (3.9+) or {**a, **b}; the right side wins. a.update(b) and a |= b change a in place.
  5. Why did settings = defaults; settings.update(user) change the defaults? Assignment doesn't copy; both names point to the same dictionary. Copy with dict(defaults) or defaults.copy().
  6. What's a shallow merge vs a deep merge? A shallow merge only looks at top-level keys, so a nested dictionary is replaced as a whole. A deep merge recurses into keys whose values are dictionaries on both sides.
  7. What's the difference between a shallow and a deep copy? dict(d) / d.copy() copy the outer dictionary but share the inner objects; copy.deepcopy(d) copies every level.
  8. How do you read a nested value safely? Split the path; at each level check isinstance(data, dict) and key in data (or catch KeyError and TypeError), returning a default.
  9. Why key in d instead of d.get(key) is None? A key can exist with the value None; in distinguishes missing from present.
  10. What's the time complexity of a dictionary lookup? O(1) on average (hash table), O(n) in the rare worst case of many hash collisions.

Glossary

Term Meaning Example
Dictionary (dict) Stores key → value pairs; keys are unique {"Asha": 90}
Key / value What you look up by / what you get back "Asha" / 90
d.items() The (key, value) pairs of a dictionary for name, mark in marks.items()
Invert a dictionary Swap keys and values {90: ['Asha', 'Neha']}
Dictionary comprehension Builds a dict in one line {v: k for k, v in d.items()}
Overwrite Assigning to an existing key replaces its value d[90] = "Neha"
d.get(k, default) The value for k, or default if k is missing marks.get("Zoya", 0)
d.setdefault(k, default) Returns d[k], inserting default first if missing d.setdefault(90, []).append("Asha")
defaultdict(list) A dict that creates [] for any missing key collections.defaultdict
Hash A number computed from a value, used to find keys fast hash("chess")
Hashable Can be a dict key or set item: its hash never changes strings, ints, tuples
Unhashable Can't be a key, because it can change lists, dicts, sets
Mutable / immutable Can / can't be changed in place list / tuple
TypeError An operation the types don't support unhashable type: 'list'
KeyError The dictionary has no such key d["phone"]
AttributeError The object has no such attribute or method "Asha".get
Merge Combine two dictionaries into one defaults | user
d.update(other) Copies other's pairs into d, in place settings.update(user)
** unpacking Spreads a dict's pairs into a new dict {**a, **b}
| / |= Dict union, a new dict / in place (Python 3.9+) a | b
Alias A second name for the same object settings = defaults
is / == Same object / equal contents settings is defaults
Shallow copy A new outer object sharing the inner ones dict(d), d.copy()
Deep copy Copies every level copy.deepcopy(d)
Shallow merge Merges top-level keys only a | b
Deep merge Recurses into nested dictionaries deep_merge(a, b)
Recursion A function that calls itself on a smaller part deep_merge(result[key], value)
isinstance(x, T) True if x is of type T isinstance({}, dict)
Nested data Dictionaries and lists inside each other an order with a customer with an address
JSON A text format for nested data used by web APIs {"id": 501, ...}
Path A list of keys joined with dots "customer.address.city"
str.split(".") Splits a string at every dot "a.b".split(".") → ['a', 'b']
Default value What to return when something is missing None, "not given"
Short-circuit and / or stop as soon as the answer is known not isinstance(...) or key not in data
EAFP / LBYL Try and catch errors / check before acting try ... except KeyError / if key in d
Leaf A value that isn't a (non-empty) dictionary "Pune"
Flatten Turn nested data into one level {"a.b": 1}
Extended unpacking *rest, last = items *parents, last = path.split(".")
Counter A dict for counting; + adds counts Counter(a) + Counter(b)
O(1) average Constant time on average a dict lookup

Summary

  • Invert a dictionary: keys are unique, so {v: k for k, v in d.items()} silently keeps only the last key for a repeated value (Asha was lost). Map each value to a list: if v not in inv: inv[v] = [], setdefault, or defaultdict(list). List values can't be keys (TypeError: unhashable type: 'list'): add one entry per item instead. O(n).
  • Merge: settings = defaults is a second name, so update changed the defaults. Build a new dict with a | b or {**a, **b}; the right side wins. Both are shallow: a nested dict is replaced whole (theme was lost). A recursive deep merge goes inside; untouched inner dicts are shared unless you copy.deepcopy.
  • Nested value by path: path.split("."), then step one level per key. [] raises KeyError, .get raises AttributeError on a string, so check isinstance(data, dict) and key in data at every level and return the default. O(k) for k keys.

Next episode: Matrix questions: transposing with zip(*m), rotating a matrix 90°, the spiral order, and the [[0] * n] * n trap where every row changes at once.