How to remove duplicate dicts in list in Python?

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.