使用不同的键在python中合并两个字典

时间:2021-02-14 10:26:21

标签: 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]}

我希望有两个值(在列表中)对于每个键。 如果键不在字典之一中,我希望它写 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 函数添加什么?

谢谢:)

2 个答案:

答案 0 :(得分:4)

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

    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
              "accept-language": "en-US,en;q=0.9", "accept-encoding": "gzip, deflate, br", "accept": "*/*"}

    URL = "https://www.nseindia.com/api/liveEquity-derivatives?index=nse50_fut"
    fut_json = requests.get(URL, headers = header).json()
    print(fut_json)


  File "C:\ProgramData\Anaconda3\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
    return self.scan_once(s, idx=_w(s, idx).end())

JSONDecodeError: Expecting value

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

get

因为迭代 dict 会迭代它的键,或者如下:

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}

因为 keys = set(d1) | set(d2) keys = set(d1).union(d2) 等的参数只需要是可迭代的,不一定是集合。

使用您的数据运行示例:

union

输出:

intersection

答案 1 :(得分:0)

您也可以无条件地设置值:

from pprint import pprint

...

for key in dict3.keys():
    dict3[key] = [dict_conv.get(key, 0), dict_org.get(key, 0)]
....

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