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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 12 views 0 copies

Python code

19 lines
Python 3.9+
def 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

stdout
[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

  1. 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])]`.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.