Convert Lists to Nested Dictionary in Python

The list is defined by an ordered sequence of elements whereas the nested dictionary defines the dictionary include another dictionary. The nested dictionary is required when we want to store large data in a big dictionary. In Python, we have some built-in functions like reduce() and zip() that Convert Lists into Nested Dictionary. For example- Dictionary data communicate the structural content of data which is easier to understand.


The following syntax is used in the examples −


This built-in function in Python follows the functools module to perform a specific operation on lists.


The zip() is a built-in function in Python that accepts any kind of parameters- lists, tuples, dictionary, sets, and, so on.

Using for Loop

The program uses the for loop to iterate the input list and sets to convert the Lists into Nested Dictionary.


In the following example, we start the program by creating the list and storing it in the variable my_list. As per the problem statement, now we will create the empty dictionary to store in the variable p_list and the same variable again stored in the variable emp_dict that represents the nesting structure. Then use the for loop that iterates the my_list of each item. Moving ahead to create the new dictionary in the variable p_list[item] and then swap this variable to the variable named p_list that will depict the nested Dictionary in Python. Finally, we are printing the result with the help of a variable named emp_dict.

my_list = ['a', 'b', 'c']
# Nesting structure
emp_dict = p_list = {}
for item in my_list:
   p_list[item] = {}
   p_list = p_list[item]


{'a': {'b': {'c': {}}}}

Using Functools Module

The following command is required to install in the system −

pip install functools

The program uses functools library that has a high level of built-in functions like reduce() to solve the conversion of lists into Nested Dictionary in Python.


In the following example, begin the program by importing the package named functools which will provide the built-in method library(). Then create the list and store it in the variable P. Next, initialize the variable Q that stores the value as reduce() function that accepts two parameters −

  • reduce(lambda x, y: {y:x}, Q[::-1]) for Q in P: The reduce function iterated the single value from left to right in the list. Then lambda function takes two arguments x and y and returns a dictionary with y as the key and x as the value. The 'Q[::-1]) for Q in P' depicts the nested dictionary structure where each structure element of the reversed list becomes a key in the dictionary.

Finally, we are printing the result with the help of Q.

# The method name reduce() from functools module()
from functools import reduce
P = [['P', 'Q', 'R'], ['M', 'N', 'O']]
Q = [reduce(lambda x, y: {y:x}, Q[::-1]) for Q in P]


[{'P': {'Q': 'R'}}, {'M': {'N': 'O'}}]

Using Dictionary Comprehension

The program uses for loop for iteration and using zip will create the dictionary conversion from lists in Python.


In the following example, we will start the program by creating the three lists in their respective variables- t1, t2, and, t3. Then create the structure of the dictionary with the help of key and value pairs i.e. a,b,c that will represent the formation of nested dictionary w.r.t the variables- t1, t2, and, t3 by using for loop and built-in method zip(). This process is known as dictionary comprehension and stores it in the variable result. Finally, we are printing the output with the help of variable result.

t1 = ['Letter', 'Word', 'Number']
t2 = ['A', 'Box', 'Integer']
t3 = [1, 3, 41905]
# create the nested dictionary by using dictionary comprehension
result = {a: {b: c} for (a, b, c) in zip(t1, t2, t3)}
print("The nesting dictionary: ", result)


The nesting dictionary:  {'Letter': {'A': 1}, 'Word': {'Box': 3}, 'Number': {'Integer': 41905}}

Using Recursion

The program uses arbitrary depth to work on converting Lists to nested Dictionary. The arbitrary depth has a similar behavior as compared to dictionary comprehension. Here it will use the recursion technique that is termed as function calling to function itself.


In the following example, the program starts with recursive Python that takes two arguments- lst( to set the list ) and d( to set the default value as 0). Then it will use the if-statement to check whether the integer d is less than the length of the list length i.e. len(lst) and if it has found less then it returns the empty dictionary. Next, the function returns the result of a nested dictionary by using dictionary comprehension with if-statement and for loop. Then create the list and store it in the variable my_lst. Now call the function named my_dict that passes the variable my_lst as a parameter and stores in the variable result. Finally, print the output with the help of variable result.

def my_dict(lst, d=0):
   # if-statement to check condition and return of nested dictionary
   if d > len(lst):
      return {}
   return {a[d]: my_dict([x for x in lst if x[d] == a[d]], d+1) for a in lst}

my_lst = [['a', 'b', 'c'], ['d', 'e', 'f']]
result = my_dict(my_lst)
print("List to Nested Dictionary:\n", result)


List to Nested Dictionary:
 {'a': {'b': {}}, 'd': {'e': {}}}


We explored the four different methods to solve the problem statement based on converting Lists to Nested Dictionary in Python. The last example was a bit different from all other examples as it uses an arbitrary depth method that shows the output of both lists and nesting dictionary whereas the previous three outputs show only nested dictionary. The lists and dictionary are known for datatypes in Python.

Updated on: 17-Jul-2023


Kickstart Your Career

Get certified by completing the course

Get Started