Convert Nested Dictionary to List in Python
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.
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 usinglist(inner.values())
.
Let's explore some more methods and see how we can convert nested dictionary to list in Python.
Table of Content
Using a Loop with append()
This method explicitly creates the result list by appending elements one by one.
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
.
Using itertools.chain
for Flattening
The itertools.chain
method is particularly useful for flattening nested structures during the conversion process.
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.
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.
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.