首页 > 解决方案 > Python - 加入包含的两个字典列表,并忽略任何不匹配的?

问题描述

我试图加入两个字典列表,其中一个字段包含另一个字段的一部分,如果没有匹配项将其删除。

list_1 = [{
    "bytes_in": 0,
    "rsrq": -50,
    "hostname": "AB9472"
},
{
    "bytes_in": 0,
    "rsrq": -90,
    "hostname": "DF4845"
},
{
    "bytes_in": 0,
    "rsrq": "None",
    "hostname": "FC4848"
}
]

list_2 = [{
    "id": 249,
    "ref_no": "AB9472 - 015632584",
    "rssi": "-75.0",
    "circuit_type": "4G"
},
{
    "id": 17,
    "ref_no": "DF4845 - 8984494",
    "rssi": "-20.0",
    "circuit_type": "4G"
}]

因此在上面的示例中,list_1 主机名字段将包含在 list_2 ref_no 中,并且将匹配前两条记录,然后在新的 list_3 中创建

我觉得我可以在 iterrtools 中做到这一点,但我不知道怎么做?谢谢

所需的输出:

list_3 = [{
    "id": 249,
    "ref_no": "AB9472 - 015632584",
    "rssi": "-75.0",
    "circuit_type": "4G",
    "bytes_in": 0,
    "rsrq": -50,
    "hostname": "AB9472"
},
{
    "id": 17,
    "ref_no": "DF4845 - 8984494",
    "rssi": "-20.0",
    "circuit_type": "4G",
    "bytes_in": 0,
    "rsrq": -90,
    "hostname": "DF4845"
}]

标签: python

解决方案


尝试这个 :

list_3 = []
for i in list_1:
    for j in list_2:
        if i['hostname'] == j['ref_no'].split("-")[0].strip():
            list_3.append({**i,**j})

print(list_3)

推荐阅读