Find different values between 2 lists of dictionaries with different keys

I have 2 lists:

list1 = [
    {
        "address": "1000",
        "amount": 0
    },
    {
        "address": "2000",
        "amount": 0
    },
    {
        "address": "3000",
        "amount": 0
    },
    {
        "address": "4000",
        "amount": 20
    }
]
list2 = [
    {
        "account": "1000",
        "balance": 100
    },
    {
        "account": "2000",
        "balance": 200
    },
    {
        "account": "3000",
        "balance": 300
    }
]

I want to search list2 and see if the value from list1 key "address" is already present in list2 as a value tied to "account" key.

If it is not, append both "address" & "amount" to list2 as "account" & "balance".

Example:

list1 "address" of 4000 is not in list2 as account: 4000, so I want to add that entire dict to list2 as:

    {
        "account": "4000",
        "balance": 20
    }

What I have tried already based on other SO questions:

def unique_values_from_list(dict_list):
    all_values = set()
    for dictionary in dict_list:
        all_values.update(dictionary.values())
    return all_values

unique_1 = unique_values_from_list(list1)
unique_2 = unique_values_from_list(list2)

intersection = unique_1.intersection(unique_2)

Which gives the values of keys: address/account that are in both lists of dicts.
But I don’t know where to go from there…

>Solution :

You might want to build a set of list2 inner dictionaries values (for the "account" key), then loop over list1:

keys2 = {d['account'] for d in list2 if 'account' in d}
# {'1000', '2000', '3000'}

out = [{'account': d['address'], 'balance': d['amount']}
       for d in list1
       if (a:=d.get('address', None)) and a not in keys2]

print(out)

Output:

[{'account': '4000', 'balance': 20}]

If you rather want to update list2:

keys2 = {d['account'] for d in list2 if 'account' in d}
# {'1000', '2000', '3000'}

for d in list1:
    if (a:=d.get('address', None)) and a not in keys2:
        list2.append({'account': d['address'], 'balance': d['amount']})

print(list2)

Output:

[{'account': '1000', 'balance': 100},
 {'account': '2000', 'balance': 200},
 {'account': '3000', 'balance': 300},
 {'account': '4000', 'balance': 20}]

Leave a Reply