簡體   English   中英

通過匹配鍵值來連接兩個dicts的值

[英]Joining values of two dicts by matching key value

我有兩個這樣的詞典:

dict1 = {'foo': {'something':'x'} }
dict2 = {'foo': {'otherthing':'y'} }

我想將這些值加在一起,以便:

dict3 = {'foo': {'something':'x', 'otherthing':'y'} }

我怎樣才能做到這一點?

注意:兩個dicts總是有匹配的鍵。

您可以嘗試使用dict理解

>>> dict1 = {'foo': {'something':'x'} }
>>> dict2 = {'foo': {'otherthing':'y'} }
>>>
>>> {key: dict(dict1[key], **dict2[key]) for key in dict1}
{'foo': {'otherthing': 'y', 'something': 'x'}}

>>> # ---Or---
>>> {keys: dict(dict1[keys].items() + dict2[keys].items()) for keys in dict1}
{'foo': {'otherthing': 'y', 'something': 'x'}}

他們只是使用兩種不同的方式來合並dicts。

您可以使用collections.defaultdict

>>> from collections import defaultdict
>>> dic = defaultdict(dict)
for k in dict1:
    dic[k].update(dict1[k])
    dic[k].update(dict2[k])
...     
>>> dic
defaultdict(<type 'dict'>,
{'foo': {'otherthing': 'y', 'something': 'x'}
})

另一種選擇,作為較短的單行詞典理解:

{ k : dict(dict2[k].items() + v.items()) for k, v in dict1.items() }

它也可以使用for循環完成:

>>> dict3 = {}
>>> for x in dict1.keys():
        for y in dict1[x].keys():
            for z in dict2[x].keys():
                dict3[x] = {y: dict1[x][y], z: dict2[x][z]}

>>> dict3
{'foo': {'otherthing': 'y', 'something': 'x'}}

暫無
暫無

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

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