通过匹配键值来连接两个dicts的值

时间:2021-04-10 18:09:37

I have two dictionaries like this:

我有两个这样的词典:

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

and i want to join the values together so that:

我想将这些值加在一起,以便:

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

How can I do this?

我怎样才能做到这一点?

Note: both dicts will always have matching keys.

注意:两个dicts总是有匹配的键。

4 个解决方案

#1


4  

You can try using dict comprehension:

您可以尝试使用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'}}

they just use two different ways to merge dicts.

他们只是使用两种不同的方式来合并dicts。

#2


2  

You can use collections.defaultdict:

您可以使用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'}
})

#3


1  

Another option, as a shorter one-liner dictionary comprehension:

另一种选择,作为较短的单行词典理解:

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

#4


1  

It can also be done using for loops:

它也可以使用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'}}

#1


4  

You can try using dict comprehension:

您可以尝试使用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'}}

they just use two different ways to merge dicts.

他们只是使用两种不同的方式来合并dicts。

#2


2  

You can use collections.defaultdict:

您可以使用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'}
})

#3


1  

Another option, as a shorter one-liner dictionary comprehension:

另一种选择,作为较短的单行词典理解:

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

#4


1  

It can also be done using for loops:

它也可以使用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'}}