How to remove duplicate dictionary based on selected keys from a list of dictionaries in Python?

I am new to Python and try to learn as much as possible. I am stuck in a stupid problem when I want to remove some dictionary entries from a list based on sample key-value pairs. For example, I have:

l = [{'A':1, 'B':2, 'C':3, 'D':4}, {'A':5, 'B':6, 'C':7, 'D':8}, {'A':1, 'B':9, 'C':3, 'D':10}] 

And the conclusion I want is to delete dictionaries based on two keys A and C values:

 l = [{'A':1, 'B':2, 'C':3, 'D':4}, {'A':5, 'B':6, 'C':7, 'D':8}] 
+5
source share
1 answer

Using set to remember if elements are visible.

 >>> A, B, C, D = 'ABCD' >>> >>> lst = [ ... {A:1, B:2, C:3, D:4}, ... {A:5, B:6, C:7, D:8}, ... {A:1, B:9, C:3, D:10} ... ] >>> seen = set() >>> [x for x in lst if [(x[A], x[C]) not in seen, seen.add((x[A], x[C]))][0]] [{'A': 1, 'C': 3, 'B': 2, 'D': 4}, {'A': 5, 'C': 7, 'B': 6, 'D': 8}] 
+5
source

Source: https://habr.com/ru/post/1240784/


All Articles