List to a nested dictionary

MediumDictionary Programs · 39 of 94

Write a Python program to convert a list into a nested dictionary of keys.

Advertisement
Input
["a", "b", "c", "d"]
Output
{'a': {'b': {'c': {'d': {}}}}}

Approach

  1. Build from the inside out: start with {} and wrap it for each key in reverse.

Solution

Python
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”: {}}}}}.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs