2 回答
TA贡献1824条经验 获得超8个赞
像这样的东西适用于任意数量的输入字典:
import collections
def merge_dicts(*args):
rtn = collections.defaultdict(list)
for input_dict in args:
for key, value in input_dict.items():
rtn[key].append(value)
return rtn
诀窍是使用该defaultdict结构在新条目不存在时自动创建新条目。在这种情况下,访问尚不存在的键会将其创建为空列表。
请注意,以上返回一个defaultdict对象。如果这是不可取的,您可以将其转换回 dict 或改用此函数:
def merge_dicts(*args):
rtn = {}
for input_dict in args:
for key, value in input_dict.items():
rtn.setdefault(key, []).append(value)
return rtn
TA贡献1840条经验 获得超5个赞
这样的事情怎么样?
from functools import reduce
def _merge_two_dicts(combined, dictionary):
for key, value in dictionary.items():
combined.setdefault(key, []).append(value)
return combined
def merge_dicts(*dicts):
return reduce(_merge_two_dicts, dicts, {})
if __name__ == '__main__':
a = {1: 'a', 2: 'b', 3: 'c'}
b = {1: 'd', 2: 'e', 3: 'f', 4: 'g'}
c = {1: 'h', 3: 'i', 5: 'j'}
combined = merge_dicts(a, b, c)
print(combined)
输出:
{1: ['a', 'd', 'h'], 2: ['b', 'e'], 3: ['c', 'f', 'i'], 4: ['g'], 5: ['j']}
添加回答
举报