将 zip 与两个不同长度的词典一起使用

using zip with two dictionaries of different length

A={1:[1],2:[2],3:[3]}

B= {1:[5]}

summ = [a[0]+b[0] for (a,b) in zip(A.values(),B.values())]

print(summ)

summ = [6]

我有上面的情况,我想将对应于相同 KEYS 的值相加 同时保留非对应的值,所以这个解决方案案例将是:

summ = [6, 2, 3]

我该怎么做?压缩字典不是强制性的,但这是我到目前为止所尝试的。

def sum_dicts(A: dict, B: dict):
    temp = {}
    for key in A.keys():
        temp[key] = A[key] + B[key] if key in B.keys() else A[key]
    
    for key in [key for key in B.keys() if key not in A.keys()]:
        temp[key] = B[key]

    return temp

此函数接受两个字典并添加两个字典中存在的键的值,当没有匹配的字典时使用每个字典的值更新临时字典。

列表理解应该可以解决问题:

summ = [v[0] + B[k][0] if k in B else v[0] for k, v in A.items()]