Get the unique values from a list of dictionaries


Python tip:

You can use a dictionary comprehension to create a list of dictionaries unique by value on a selected key

users = [
    {"name": "John Doe", "email": "[email protected]"},
    {"name": "Mary Doe", "email": "[email protected]"},
    {"name": "Mary A. Doe", "email": "[email protected]"},
]


print(list({user["email"]: user for user in users}.values()))

"""
[
    {'name': 'John Doe', 'email': '[email protected]'},
    {'name': 'Mary A. Doe', 'email': '[email protected]'}
]

The same key can occur only once inside a dictionary.
Every element from a list is assigned to a key with a value of email.
Each new element with the same email overwrites any existing ones.
Therefore, only one element is left with the same value on the key.

.values() returns a dict_values object containing values from the dictionary,
list() converts the dict_values object back to a list.
"""