Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Extract Unique dictionary values in Python Program
When it is required to extract unique values from a dictionary, there are several approaches available. The most effective method combines set comprehension with sorted() to eliminate duplicates and arrange values in order.
Using Set Comprehension with Sorted
This approach flattens all dictionary values into a set (removing duplicates) and then sorts them ?
my_dict = {'hi': [5, 3, 8, 0],
'there': [22, 51, 63, 77],
'how': [7, 0, 22],
'are': [12, 11, 45],
'you': [56, 31, 89, 90]}
print("The dictionary is:")
print(my_dict)
# Extract unique values using set comprehension
my_result = list(sorted({elem for val in my_dict.values() for elem in val}))
print("The unique values are:")
print(my_result)
The dictionary is:
{'hi': [5, 3, 8, 0], 'there': [22, 51, 63, 77], 'how': [7, 0, 22], 'are': [12, 11, 45], 'you': [56, 31, 89, 90]}
The unique values are:
[0, 3, 5, 7, 8, 11, 12, 22, 31, 45, 51, 56, 63, 77, 89, 90]
Using itertools.chain
Alternative approach using itertools.chain() to flatten the lists ?
import itertools
my_dict = {'hi': [5, 3, 8, 0],
'there': [22, 51, 63, 77],
'how': [7, 0, 22]}
print("The dictionary is:")
print(my_dict)
# Flatten and get unique values
flattened = itertools.chain.from_iterable(my_dict.values())
unique_values = sorted(set(flattened))
print("The unique values are:")
print(unique_values)
The dictionary is:
{'hi': [5, 3, 8, 0], 'there': [22, 51, 63, 77], 'how': [7, 0, 22]}
The unique values are:
[0, 3, 5, 7, 8, 22, 51, 63, 77]
How It Works
The
my_dict.values()method accesses all lists in the dictionarySet comprehension
{elem for val in my_dict.values() for elem in val}flattens all lists and removes duplicatesThe
sorted()function arranges unique values in ascending orderConverting to
list()provides the final result as a list
Comparison
| Method | Readability | Performance | Memory Usage |
|---|---|---|---|
| Set Comprehension | Good | Fast | Low |
| itertools.chain | Excellent | Fast | Very Low |
Conclusion
Set comprehension with sorted() provides an efficient way to extract unique values from dictionary lists. For better readability with large datasets, consider using itertools.chain() for flattening operations.
