We are given a dictionary where the values are lists and our task is to retrieve all the values as a single flattened list. For example, given the dictionary: d = {"a": [1, 2], "b": [3, 4], "c": [5]} the expected output is: [1, 2, 3, 4, 5]
Using itertools.chain()
itertools.chain() function efficiently combines multiple lists into a single iterable without extra memory overhead.
from itertools import chain
d = {"a": [1, 2], "b": [3, 4], "c": [5]}
res = list(chain(*d.values()))
print(res)
Output
[1, 2, 3, 4, 5]
Explanation:
- d.values() retrieves all the dictionary values as separate lists and chain(*d.values()) flattens them efficiently.
- list() converts the result into a list.
Using sum()
sum() function can concatenate all lists into a single flattened list.
d = {"a": [1, 2], "b": [3, 4], "c": [5]}
res = sum(d.values(), [])
print(res)
Output
[1, 2, 3, 4, 5]
Explanation:
- d.values() retrieves all dictionary values as separate lists.
- sum(d.values(), []) flattens them by adding each list to an empty list ([]).
Using List Comprehension
List comprehension allows us to flatten dictionary values into a single list in a readable way.
d = {"a": [1, 2], "b": [3, 4], "c": [5]}
res = [val for sublist in d.values() for val in sublist]
print(res)
Output
[1, 2, 3, 4, 5]
Explanation:
- d.values() retrieves all dictionary values as separate lists and the first loop iterates over each list (sublist).
- whereas the second loop extracts each element (val) from the sublist and adds it to res.