Categories
Python Answers

How to remove duplicate dicts in list in Python?

Spread the love

Sometimes, we want to remove duplicate dicts in list in Python.

In this article, we’ll look at how to remove duplicate dicts in list in Python.

How to remove duplicate dicts in list in Python?

To remove duplicate dicts in list in Python, we can use list comprehension.

For instance, we write:

d = [{'a': 123}, {'b': 123}, {'a': 123}]
no_dups = [i for n, i in enumerate(d) if i not in d[n + 1:]]
print(no_dups)

We have the d list with duplicate dicts.

Then we use not in d[n + 1:] to filter out the dicts that are duplicates of the dict in index i.

And then we assign the resulting list to no_dups.

Therefore, no_dups is:

[{'b': 123}, {'a': 123}]

Conclusion

To remove duplicate dicts in list in Python, we can use list comprehension.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *