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_dictionary iterates through each dictionary in the list

  • for value in element.values() extracts all values from the current dictionary

  • set() automatically removes duplicate values (11, 22 appear multiple times)

  • list() converts the set back to a list for further operations

  • sort() 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.

Updated on: 2026-03-26T01:45:09+05:30

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements