Python Practice › Dictionary Programs › Program 39
List to a nested dictionary
Write a Python program to convert a list into a nested dictionary of keys.
Input
["a", "b", "c", "d"]
Output
{'a': {'b': {'c': {'d': {}}}}}Approach
- Build from the inside out: start with {} and wrap it for each key in reverse.
Solution
keys = ["a", "b", "c", "d"]nested = {}for key in reversed(keys): nested = {key: nested}print(nested)Output
{'a': {'b': {'c': {'d': {}}}}}Line by line
Lines 3-4
Starting from “d” and wrapping outwards gives {“a”: {“b”: {“c”: {“d”: {}}}}}.
Learn the concept
New to this topic? Read the lesson, then come back.