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
Python – Dictionaries with Unique Value Lists
When working with a list of dictionaries, you may need to extract all unique values from across all dictionaries. Python provides an elegant solution using set operations and list comprehensions to eliminate duplicates efficiently.
Example
Below is a demonstration of extracting unique values from dictionary lists ?
my_dictionary = [{'Python': 11, 'is': 22}, {'fun': 11, 'to': 33}, {'learn': 22}, {'object': 9}, {'oriented': 11}]
print("The dictionary is:")
print(my_dictionary)
my_result = list(set(value for element in my_dictionary for value in element.values()))
print("The resultant list is:")
print(my_result)
print("The resultant list after sorting is:")
my_result.sort()
print(my_result)
The dictionary is:
[{'Python': 11, 'is': 22}, {'fun': 11, 'to': 33}, {'learn': 22}, {'object': 9}, {'oriented': 11}]
The resultant list is:
[33, 11, 22, 9]
The resultant list after sorting is:
[9, 11, 22, 33]
How It Works
The solution uses a nested generator expression inside a set() constructor:
for element in my_dictionaryiterates through each dictionary in the listfor value in element.values()extracts all values from the current dictionaryset()automatically removes duplicate values (11, 22 appear multiple times)list()converts the set back to a list for further operationssort()arranges the unique values in ascending order
Alternative Method Using Chain
You can also use itertools.chain for a more readable approach ?
from itertools import chain
my_dictionary = [{'Python': 11, 'is': 22}, {'fun': 11, 'to': 33}, {'learn': 22}, {'object': 9}, {'oriented': 11}]
# Extract all values and get unique ones
all_values = chain.from_iterable(d.values() for d in my_dictionary)
unique_values = sorted(set(all_values))
print("Unique values using chain:")
print(unique_values)
Unique values using chain: [9, 11, 22, 33]
Conclusion
Use set() with generator expressions to extract unique values from dictionary lists efficiently. The itertools.chain method provides better readability for complex nested iterations.
