簡體   English   中英

如何根據匹配鍵將一個字典中的值添加到另一個字典中?

[英]How to add values from one dictionary to another based on matching keys?

我有兩個具有匹配鍵和不同值的字典。 我想將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:3:[“ g”,“ c”]}

而是不附加值。 我也嘗試在v周圍使用方括號,該括號將返回

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

我想這就是您想要的...我使用字符串作為原始值,但仍可用於列表。

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

這是您想要的嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM