Python problem 26 of 30

Flatten a dictionary

  • Python
  • Hard

Write flatten_dict(d) that turns nested dictionaries into a single level, joining the keys on the path with dots.

flatten_dict({"a": 1, "b": {"c": 2, "d": {"e": 3}}})
# {"a": 1, "b.c": 2, "b.d.e": 3}
Show hint

Recurse into any value that is itself a dictionary, passing along the key path built so far.

Show solution
def flatten_dict(d, prefix=""):
    out = {}
    for key, value in d.items():
        name = f"{prefix}.{key}" if prefix else key
        if isinstance(value, dict):
            out.update(flatten_dict(value, name))
        else:
            out[name] = value
    return out

Each call handles one level and hands nested dictionaries to a recursive call with a longer prefix. Every value is visited once. Two edge cases are worth knowing: an empty nested dictionary disappears completely, and keys that already contain dots become ambiguous. This shape comes up constantly when turning JSON into table columns.

Want a problem like this every day? See today's problem and keep a streak going.