How can I remove duplicate dict in list in Python

+1 vote
I have a list of dicts, and I'd like to remove the dicts with identical key and value pairs.

For this list: [{'a': 123}, {'b': 123}, {'a': 123}]

I'd like to return this: [{'a': 123}, {'b': 123}]
Nov 19, 2018 in Python by Anirudh
• 2,090 points
9,290 views

3 answers to this question.

+1 vote

You can preserve the Order, then you can do:

from collections import OrderedDict
print OrderedDict((frozenset(item.items()),item) for item in data).values()
# [{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}]

If the order doesn't matter, then you can do:

print {frozenset(item.items()):item for item in data}.values()
# [{'a': 3222, 'b': 1234}, {'a': 123, 'b': 1234}]
answered Nov 19, 2018 by Nymeria
• 3,560 points
+2 votes
[dict(t) for t in {tuple(d.items()) for d in l}]

or

a = [{'a': 123}, {'b': 123}, {'a': 123}]
b = []
for i in range(0, len(a)):
    if a[i] not in a[i+1:]:
        b.append(a[i])
answered Aug 15, 2019 by anonymous

edited Aug 20, 2019 by Kalgi
This is so much easier than @Nymeria's answer. The logic is clear and understandable. Thanks!
0 votes
use list comprehension. much simpler:

a = [{'a': 123}, {'b': 123}, {'a': 123}]
b = []
[b.append(item) for item in a if item not in b]
b
answered Aug 3, 2020 by everything_is_simple

Related Questions In Python

0 votes
1 answer

How can I convert a list of dictionaries from a CSV into a JSON object in Python?

You could try using the AST module. ...READ MORE

answered Apr 17, 2018 in Python by anonymous
3,459 views
0 votes
2 answers

How can I get the count of a list in Python?

n=[1,2,3,4,5,6,7,8,9] print(len(n)) =9 READ MORE

answered Dec 10, 2020 in Python by anonymous
1,486 views
+1 vote
1 answer

How can I reverse list in Python?

Reversing a list is a commonly used ...READ MORE

answered May 13, 2019 in Python by Taj
• 1,080 points
985 views
0 votes
1 answer
0 votes
1 answer
+1 vote
4 answers

How do I remove an element from a list by index in Python?

Delete the List and its element: We have ...READ MORE

answered Jun 7, 2020 in Python by sahil
• 500 points
280,722 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP