首页 > 解决方案 > 在python中使用不同的键合并两个字典

问题描述

我有两个字典:

dict_conv
Out[162]: 
{'Alanine, aspartate and glutamate metabolism': 4,
 'Ascorbate and aldarate metabolism': 4,
 'Benzoate degradation': 6,
 'Biosynthesis of antibiotics': 16}

dict_org
Out[163]: 
{'Amino sugar and nucleotide sugar metabolism': 5,
 'Arginine and proline metabolism': 4,
 'Biosynthesis of antibiotics': 11,
 'Biosynthesis of secondary metabolites': 21}

我想把它们结合起来。我确实喜欢这样:

def mergeDict(dict_conv, dict_org):
   ''' Merge dictionaries and keep values of common keys in list'''
   dict3 = {**dict_conv, **dict_org}
   for key, value in dict3.items():
       if key in dict_conv and key in dict_org:
               dict3[key] = [value , dict_conv[key]]
   return dict3

dict3 = mergeDict(dict_conv, dict_org)

并得到了这个字典:

dict3
Out[164]: 
{'Alanine, aspartate and glutamate metabolism': 4,
 'Ascorbate and aldarate metabolism': 4,
 'Benzoate degradation': 6,
 'Biosynthesis of antibiotics': [11, 16],
 'Biosynthesis of secondary metabolites': [21, 26]}

我想为每个 key有两个值(在列表中) 。如果密钥不在其中一个字典中,我希望它写为 0,如下所示:

dict3
    Out[164]: 
    {'Alanine, aspartate and glutamate metabolism': [4,0],
     'Amino sugar and nucleotide sugar metabolism': [0,5],
     'Ascorbate and aldarate metabolism': [4,0],
     'Benzoate degradation': [6,0],
     'Biosynthesis of antibiotics': [11, 16],
     'Biosynthesis of secondary metabolites': [0,21]}

(第一个值代表“dict_conv”值,第二个代表“dict_org”值)

我应该在mergeDict函数中添加什么?

谢谢你 :)

标签: python

解决方案


您可以简单地构建一组所有键,然后使用getdicts 的方法创建列表,默认值为 0:

def merge(d1, d2):
    keys = set(d1.keys()) | set(d2.keys())
    return {key: [d1.get(key, 0), d2.get(key, 0)] for key in keys}

正如@Stephan B 所建议的那样,第一行可以用更短的方式编写:

keys = set(d1) | set(d2)

因为迭代一个 dict 迭代它的键,或者作为:

keys = set(d1).union(d2)

因为 , 等的参数union只需intersection要是一个可迭代的,而不一定是一个集合。

使用您的数据运行示例:

d1 = {'Alanine, aspartate and glutamate metabolism': 4,
     'Ascorbate and aldarate metabolism': 4,
     'Benzoate degradation': 6,
     'Biosynthesis of antibiotics': 16}

d2 = {'Amino sugar and nucleotide sugar metabolism': 5,
     'Arginine and proline metabolism': 4,
     'Biosynthesis of antibiotics': 11,
     'Biosynthesis of secondary metabolites': 21}

print(merge(d1, d2))

输出:

{'Biosynthesis of antibiotics': [16, 11], 
'Amino sugar and nucleotide sugar metabolism': [0, 5], 
'Arginine and proline metabolism': [0, 4], 
'Alanine, aspartate and glutamate metabolism': [4, 0], 
'Ascorbate and aldarate metabolism': [4, 0], 
'Benzoate degradation': [6, 0], 
'Biosynthesis of secondary metabolites': [0, 21]}

推荐阅读