We are given dictionary of dictionaries we need to convert it to list of dictionaries. For example, For example, we are having d = { 'A': {'color': 'red', 'shape': 'circle'}, 'B': {'color': 'blue', 'shape': 'square'}, 'C': {'color': 'green', 'shape': 'triangle'} } we need to convert it to a list of dictionaries so that the output becomes [{'color': 'red', 'shape': 'circle'}, {'color': 'blue', 'shape': 'square'}, {'color': 'green', 'shape': 'triangle'}].
Using List Comprehension
list comprehension iterates over the values of the dictionary which are the inner dictionaries and constructs a list of these inner dictionaries. This allows for a concise conversion of a dictionary of dictionaries into a list of dictionaries.
d = {
'A': {'color': 'red', 'shape': 'circle'},
'B': {'color': 'blue', 'shape': 'square'},
'C': {'color': 'green', 'shape': 'triangle'}
}
# Convert dictionary of dictionaries to a list of dictionaries using list comprehension
res = [val for val in d.values()]
print(res)
Output
[{'color': 'red', 'shape': 'circle'}, {'color': 'blue', 'shape': 'square'}, {'color': 'green', 'shape': 'triangle'}]
Explanation:
dretrieves the values (which are dictionaries) of the outer dictionary.- List comprehension collects these dictionaries into a list.
Using map()
map() function applies a lambda function to each value in the dictionary, where each value is an inner dictionary. lambda x: x returns the inner dictionaries and list() converts the result from map() into a list of dictionaries.
d = {
'A': {'color': 'red', 'shape': 'circle'},
'B': {'color': 'blue', 'shape': 'square'},
'C': {'color': 'green', 'shape': 'triangle'}
}
# Convert dictionary of dictionaries to a list of dictionaries
res = list(map(lambda x: x[1], d.items()))
print(res)
Output
[{'color': 'red', 'shape': 'circle'}, {'color': 'blue', 'shape': 'square'}, {'color': 'green', 'shape': 'triangle'}]
Explanation:
dreturns each key-value pair from the outer dictionary.map()is used to extract only the values (which are the inner dictionaries) and convert them into a list.
Using for Loop
for loop iterates over the values of the dictionary (which are the inner dictionaries) and creates a list containing those inner dictionaries, resulting in a list of dictionaries
d = {
'A': {'color': 'red', 'shape': 'circle'},
'B': {'color': 'blue', 'shape': 'square'},
'C': {'color': 'green', 'shape': 'triangle'}
}
# Convert dictionary of dictionaries to a list of dictionaries
res = []
for key, value in d.items():
res.append(value)
print(res)
Output
[{'color': 'red', 'shape': 'circle'}, {'color': 'blue', 'shape': 'square'}, {'color': 'green', 'shape': 'triangle'}]
Explanation: for loop iterates over the items in d , appending each inner dictionary to the result list.