python - 在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
函数中添加什么?
谢谢你 :)
解决方案
您可以简单地构建一组所有键,然后使用get
dicts 的方法创建列表,默认值为 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]}
推荐阅读
- elasticsearch - 无法将事件索引到 Elasticsearch Status=400,action=index,id=nil
- numpy - 我已经安装了 pipwin 但在安装 pyaudio 时遇到问题,显示 pipwin 无法识别
- html - 根据所选选项更改输入最大值
- r - 用预测值计算置信区间
- batch-file - win批处理命令中的转义空格字符
- javascript - 如何使用javascript从本地文件夹中获取json数据?
- swift - 如何根据单元格中的内容设置 UICollectionViewCell 的高度?
- python - 如何不计算负输入
- python - 具有自定义分位数的 Groupby 数据框并将分位数标签添加到新列
- amazon-web-services - AWS API Gateway - 设置跨账户访问的问题