Home > Blockchain >  Check if a set of key/values in dict list is in another list
Check if a set of key/values in dict list is in another list

Time:05-16

I have a list as follows:

[
  {
   'Name': 'Name1',
   'Address': 'Address1'
  },
 {
   'Name': 'Name2',
   'Postcode': 'MyPostcode'
  }
]

And another list like this:

  [
    {
    'Name': 'Name1', 
    'data' : {
    'Address': 'Address1', 
    'Postcode': 'Whatever'
    },
   {
    'Name': 'Name2', 
    'data' : {
    'Address': 'Whatever', 
    'Postcode': 'MyPostcode'
    },
   {
    'Name': 'Name3', 
    'data' : {
    'Address': 'Whatever', 
    'Postcode': 'Whatever'
    },
    ] 

For any of the items in the first list, I need to check if that combination of key/value exists in the second, and if so, delete it from the second

I can do it in multiple lines of codes, with different for loops, but probably there is a wiser way of doing it. Can anybody suggest an elegant solution?

In the example above, it should delete the two first dicts from the list and return a list only with the third one

       [
{
    'Name': 'Name3', 
    'data' : {
    'Address': 'Whatever', 
    'Postcode': 'Whatever'
    }
    ] 

Thanks

CodePudding user response:

Try:

lst1 = [
    {"Name": "Name1", "Address": "Address1"},
    {"Name": "Name2", "Postcode": "MyPostcode"},
]

lst2 = [
    {"Name": "Name1", "data": {"Address": "Address1", "Postcode": "Whatever"}},
    {
        "Name": "Name2",
        "data": {"Address": "Whatever", "Postcode": "MyPostcode"},
    },
    {"Name": "Name3", "data": {"Address": "Whatever", "Postcode": "Whatever"}},
]

out = []
for d2 in lst2:
    t = set({"Name": d2["Name"], **d2["data"]}.items())
    for d1 in lst1:
        if t.issuperset(d1.items()):
            break
    else:
        out.append(d2)

print(out)

Prints:

[{'Name': 'Name3', 'data': {'Address': 'Whatever', 'Postcode': 'Whatever'}}]
  • Related