How to Print Unique Values from a List of Dictionaries in Python?

Estimated read time 1 min read

To print unique values from a list of dictionaries in Python, you can use a combination of a set and a loop. Here is an example:

people = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 30},
    {'name': 'Charlie', 'age': 25},
    {'name': 'Alice', 'age': 25},
    {'name': 'David', 'age': 35},
    {'name': 'Alice', 'age': 30}
]

unique_ages = set()
for person in people:
    unique_ages.add(person['age'])

print(unique_ages)

In this example, the people list contains six dictionaries, each representing a person with a name and an age. The goal is to print the unique ages in the list.

To do this, we first create an empty set called unique_ages. Then we use a for loop to iterate over each person in the people list. For each person, we access their age using the dictionary key age, and add it to the unique_ages set using the add() method. Since sets only contain unique elements, this ensures that only unique ages are added to the set.

Finally, we print the contents of the unique_ages set using the print() function. This will output the unique ages in the list of dictionaries. In this example, the output will be {25, 30, 35}.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply