How to get a list of unique dictionaries with Python?

Sometimes, we want to get a list of unique dictionaries with Python.

In this article, we’ll look at how to get a list of unique dictionaries with Python.

How to get a list of unique dictionaries with Python?

To get a list of unique dictionaries with Python, we can use dict comprehension.

For instance, we write

L = [
    {'id':1,'name':'john', 'age':34},
    {'id':1,'name':'john', 'age':34},
    {'id':2,'name':'hanna', 'age':30},
    ] 
uniques = list({v['id']:v for v in L}.values())

to get the unique dictionaries with

{v['id']:v for v in L}

which creates a dictionary with the key being the id value of the dicts in L.

And we set v to the dict with the given 'id' value.

Then we call values to get the values from the returned dict which has the unique dictionaries.

Conclusion

To get a list of unique dictionaries with Python, we can use dict comprehension.