How to Flatten List of Dict Values in Python
This code flattens the values of a list of dictionaries into a single list, handling both list values and scalar values.
Python code
19 linesdef flatten_dict_values(dicts):
flattened = []
for d in dicts:
for value in d.values():
if isinstance(value, list):
flattened.extend(value)
else:
flattened.append(value)
return flattened
if __name__ == "__main__":
data = [
{"a": [1, 2], "b": [3]},
{"c": 4, "d": [5, 6]},
{"e": "x", "f": [7]},
]
result = flatten_dict_values(data)
print(result)
Output
[1, 2, 3, 4, 5, 6, 'x', 7]
How it works
The function iterates over each dictionary in the input list. For every dictionary, it checks each value: if the value is a list, it uses extend() to add all its elements to the flattened list; otherwise it uses append() to add the scalar value directly. This approach preserves the insertion order of the values from the original dictionaries. The isinstance() check is crucial to distinguish between list and scalar values, ensuring lists are unpacked while other types are added as-is.
Common mistakes
- Forgetting that `extend()` adds each element individually, while `append()` adds the whole list as one element.
- Using `flattened.extend(d.values())` which would treat each value as a single element, even if it's a list.
- Not handling non-list iterable values like tuples, which would not be flattened (only lists are handled).
Variations
- Use a list comprehension with nested loops: `[item for d in dicts for value in d.values() for item in (value if isinstance(value, list) else [value])]`.
- Use `itertools.chain` to flatten lists: `list(chain.from_iterable(v if isinstance(v, list) else [v] for d in dicts for v in d.values()))`.
Real-world use cases
- Combining values from multiple API response objects into a single list for further processing.
- Aggregating configuration values from a list of settings dictionaries into a flat list for validation.
- Extracting all attribute values from a collection of objects stored as dictionaries into a single list for analytics.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.