Dhruv Ghulati Dhruv Ghulati - 3 months ago 10
Python Question

Check two list of dicts and filter one list to remove dicts that appear in other list

I have two lists:

a = [{'val': 'abc', 'locval': {'China':24},'key3': 'meh'},{'val': 'men', 'locval': {'China':24},'key3': 'bla'},{'val': 'men', 'locval': {'India':56},'key3': 'cheh'}]
b = [{'val': 'abc', 'locval': {'China':24},'key3': 'cheh'}, {'val': 'def', 'locval': {'India':56},'key3': 'men'}]


And want to remove certain items from list A (I don't mind creating a new list) that essentially are the same as the items in list B based on two specific keys -
locval
and
val
. For example, the new list should become:

newa = [{'val': 'men', 'locval': {'China':24},'key3': 'bla'},{'val': 'men', 'locval': {'India':56},'key3': 'cheh'}]


How do I do this?

Answer

You can make a set of all the pairs of interesting key/value pairings from the b list of dicts then only keep dicts from a that do not have the same key/value pairings:

a = [{'val': 'abc', 'locval': {'China':24},'key3': 'meh'},{'val': 'men', 'locval': {'China':24},'key3': 'bla'},{'val': 'men', 'locval': {'India':56},'key3': 'cheh'}]

b = [{'val': 'abc', 'locval': {'China':24},'key3': 'cheh'}, {'val': 'def', 'locval': {'India':56},'key3': 'men'}]


st = {(tuple(d["locval"].items()), d["val"]) for d in b}

a[:] = (d for d in a if (tuple(d["locval"].items()), d["val"])  not in st)

print(a)
Comments