如何根据匹配键将一个字典中的值添加到另一个字典中?

时间:2019-01-25 23:39:12

标签: python dictionary append

我有两个字典,它们具有匹配的键和不同的值。我想将a的值添加到b。

某些键在字典a中而不在b中。我想跳过这些。

a = {1:"a", 2:"b", 3:"c", 4:"d"}
b = {1:"e", 2:"f", 3:"g"}



for k, v in a.items():
    if k in b.keys():
        list(b).append(v)
    else: print 'Could not locate key', k

我希望输出是     b = {1:[“ e”,“ a”],2:[“ b”,“ f”],3:[“ g”,“ c”]}

相反,这些值未附加。我也尝试在v周围使用方括号,该括号将返回

TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'

3 个答案:

答案 0 :(得分:0)

我认为这就是您想要的...我使用字符串作为原始值,但仍可用于列表。

>>> a = {"1":"a", "2":"b", "3": "c", "4":"d"}
>>> b = {"1":"e", "2":"f", "3":"g"}
>>> for k, v in a.items():
...     if k in b:
...         b[k] = [a[k], b[k]]
... 
>>> b
{'1': ['a', 'e'], '2': ['b', 'f'], '3': ['c', 'g']}

答案 1 :(得分:0)

这是您想要的吗?

a = {1:"a", 2:"b", 3:"c", 4:"d"}
b = {1:"e", 2:"f", 3:"g"}
c={}

keys = set(list(a.keys())+list(b.keys()))

for key in keys:
    items = []
    items += [a[key]] if key in a else []
    items += [b[key]] if key in b else []
    c[key]=items

答案 2 :(得分:0)

    a = {1:"a", 2:"b", 3:"c", 4:"d"}
    b = {1:"e", 2:"f", 3:"g"}

    for k, v in a.items():
        if k in b.keys():
            b[k] = [v,b[k]]
        else: print('Could not locate key', k)
    print(b)

output :
Could not locate key 4
{1: ['a', 'e'], 2: ['b', 'f'], 3: ['c', 'g']}

使用b [k] = [v,b [k]]代替list(b).append(v)

list(b).append(v)表示您要创建字典b的键列表,然后将v附加到该键

b [k] = [v,b [k]]意味着为键k创建字典a和b的值列表,并在键k处分配给字典b