![]() |
VOOZH | about |
In this article, we explain several efficient methods to extract unique values from the values of a dictionary in Python.
Example:
Input: data = {'gfg' : [5,6,7,8],' is' : [10,11,7,5], 'best' : [6,12,10,8], 'for' : [1,2,5]}
Output: [1, 2, 5, 6, 7, 8, 10, 11, 12]
Flatten all lists using sum() and eliminate duplicates using set(). It’s a quick, one-line method ideal for small-to-medium datasets.
[1, 2, 5, 6, 7, 8, 10, 11, 12]
Explanation:
This method uses set comprehension for compact and efficient flattening of nested lists, followed by sorting for ordered output.
[1, 2, 5, 6, 7, 8, 10, 11, 12]
Explanation:
This approach avoids intermediate lists, making it memory-efficient. chain() directly combines all lists into one sequence.
[1, 2, 5, 6, 7, 8, 10, 11, 12]
Explanation: chain(*data.values()): flattens all value lists without creating intermediate lists.
Counter() counts how many times each element appears, and its keys give the unique values directly.
[1, 2, 5, 6, 7, 8, 10, 11, 12]
Explanation:
This method creates a unique list manually by using extend() to combine lists and adding elements only if they aren’t already present.
[1, 2, 5, 6, 7, 8, 10, 11, 12]
Explanation: extend(): merges all lists into one.
This method manually checks for duplicates using countOf() instead of direct membership testing to ensure each element is added only once.
[1, 2, 5, 6, 7, 8, 10, 11, 12]
Explanation: