Convert Nested Dictionary to List in Python
Last Updated :
30 Dec, 2024
In this article, we’ll explore several methods to Convert Nested Dictionaries to a List in Python. List comprehension is the fastest and most concise way to convert a nested dictionary into a list.
Python
a = {
"a": {"x": 1, "y": 2},
"b": {"x": 3, "y": 4},
}
# Convert nested dictionary to a list of lists
res = [[key] + list(inner.values()) for key, inner in a.items()]
print(res)
Output[['a', 1, 2], ['b', 3, 4]]
Explanation:
a.items()
method iterates over the dictionary, providing both keys (key
) and values (inner
).+
operator combines the key (as a single-element list) with the inner dictionary's values, converted to a list using list(inner.values())
.
Let's explore some more methods and see how we can convert nested dictionary to list in Python.
Using a Loop with append()
This method explicitly creates the result list by appending elements one by one.
Python
a = {
"a": {"x": 1, "y": 2},
"b": {"x": 3, "y": 4},
}
result = []
# Iterate through the dictionary and construct the result list
for key, inner in a.items():
result.append([key] + list(inner.values()))
print(result)
Output[['a', 1, 2], ['b', 3, 4]]
Explanation:
- An empty list
result
is created to store the output. - The
for
loop iterates over each key-value pair in the dictionary.. - Each key and its associated values are appended as a sublist to
result
.
The itertools.chain
method is particularly useful for flattening nested structures during the conversion process.
Python
from itertools import chain
a = {
"a": {"x": 1, "y": 2},
"b": {"x": 3, "y": 4},
}
# Flatten the nested dictionary and convert it to a list
result = list(chain.from_iterable([[key] + list(inner.values()) for key, inner in a.items()]))
print(result)
Output['a', 1, 2, 'b', 3, 4]
Explanation:
- The
chain.from_iterable
function flattens the result of a generator expression. - This method is efficient when dealing with larger datasets where flattening is required.
- It produces a single flattened list from the nested dictionary structure.
Using map() for functional programming
The map()
function applies a transformation to each key-value pair, providing a functional programming alternative.
Python
a = {
"a": {"x": 1, "y": 2},
"b": {"x": 3, "y": 4},
}
# Use map to transform the dictionary into a list of lists
result = list(map(lambda item: [item[0]] + list(item[1].values()), a.items()))
# Print the result
print(result)
Output[['a', 1, 2], ['b', 3, 4]]
Explanation:
- The
lambda
function processes each key-value pair (item
), combining the key and the inner values into a new list. map()
applies the transformation to all key-value pairs, and list()
converts the result to a list.
Using Recursion
For deeply nested dictionaries, recursion can be used to convert all nested structures into lists. However, it is less efficient due to repeated function calls.
Python
def convert_to_list(d):
result = []
for key, value in d.items():
if isinstance(value, dict):
result.append([key] + convert_to_list(value))
else:
result.append([key, value])
return result
a = {
"a": {"x": 1, "y": 2},
"b": {"x": 3, "y": 4},
}
result = convert_to_list(a)
print(result)
Output[['a', ['x', 1], ['y', 2]], ['b', ['x', 3], ['y', 4]]]
Explanation:
- The function calls itself for every nested dictionary, breaking it into smaller pieces until all levels are processed.
Similar Reads
Convert a Dictionary to a List in Python In Python, dictionaries and lists are important data structures. Dictionaries hold pairs of keys and values, while lists are groups of elements arranged in a specific order. Sometimes, you might want to change a dictionary into a list, and Python offers various ways to do this. How to Convert a Dict
3 min read
Convert List of Lists to Dictionary - Python We are given list of lists we need to convert it to python . For example we are given a list of lists a = [["a", 1], ["b", 2], ["c", 3]] we need to convert the list in dictionary so that the output becomes {'a': 1, 'b': 2, 'c': 3}. Using Dictionary ComprehensionUsing dictionary comprehension, we ite
3 min read
Convert a List to Dictionary Python We are given a list we need to convert the list in dictionary. For example, we are given a list a=[10,20,30] we need to convert the list in dictionary so that the output should be a dictionary like {0: 10, 1: 20, 2: 30}. We can use methods like enumerate, zip to convert a list to dictionary in pytho
2 min read
Convert Dictionary to String List in Python The task of converting a dictionary to a string list in Python involves transforming the key-value pairs of the dictionary into a formatted string and storing those strings in a list. For example, consider a dictionary d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}. Converting this to a st
3 min read
Python - Convert List to List of dictionaries We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
4 min read