在具有不同键的 2 个字典列表之间找到不同的值

问题描述 投票:0回答:3

我有 2 个列表:

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
    }
]

我想搜索

list2
并查看
list1
键“地址”的值是否已经存在于
list2
中作为与“帐户”键绑定的值。

如果不是,请将“地址”和“金额”都附加到

list2
作为“帐户”和“余额”。

例子:

list1
4000 的“地址”不在
list2
作为
account: 4000
,所以我想将整个字典添加到
list2
作为:

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

我已经根据其他 SO 问题尝试过什么:

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)

给出了键的值:

address
/
account
,它们在两个字典列表中。 但我不知道从那里去哪里......

python list dictionary intersection difference
3个回答
2
投票

您可能想要构建一组

list2
内部字典值(对于“account”键),然后遍历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)

输出:

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

如果您想更新

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)

输出:

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

0
投票

另一种工作方法是将 list1 和 list 2 转换为字典,并用第二个字典更新第一个字典:

dict1 = {e['address']:e['amount'] for e in list1}
dict2 = {e['account']:e['balance'] for e in list2}
dict1.update(dict2)

# {'1000': 100, '2000': 200, '3000': 300, '4000': 20}

然后,如果您愿意,可以将 dict1 转回列表(尽管保持原样可能更容易使用):

list3 = [{'account':key, 'balance':val} for key, val in dict1.items()]

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

0
投票

您可以搜索list1中不在list2中的address值,并将它们附加到list2中。

for i in list1:
  if i.get("address") not in list(value['account'] for value in list2):
    list2.append({"account": i.get("address"), "balance": i.get("amount")})
print(list2)

输出:

[{'account': '1000', 'balance': 100}, {'account': '2000', 'balance': 200}, {'account': '3000', 'balance': 300}, {'account': '4000', 'balance': 20}]
© www.soinside.com 2019 - 2024. All rights reserved.