Python 用setten键理解新词典
我有两本字典:Python 用setten键理解新词典,python,python-2.7,dictionary,dictionary-comprehension,Python,Python 2.7,Dictionary,Dictionary Comprehension,我有两本字典: dict1 = {'id': 1001, 'text': 'some text 1', 'key1': 11, 'key2': 12} dict2 = {'id': 1002, 'text': 'some text 2', 'key1': 1, 'key2': 2} 我想得到这样的结果,从dict1中保留'id',然后减去'key1'和'key2': dict3 = {'id': 1001, 'key1': 10, 'key2': 10 } 我尝试了以下方法: dict3 =
dict1 = {'id': 1001, 'text': 'some text 1', 'key1': 11, 'key2': 12}
dict2 = {'id': 1002, 'text': 'some text 2', 'key1': 1, 'key2': 2}
我想得到这样的结果,从dict1中保留'id'
,然后减去'key1'
和'key2'
:
dict3 = {'id': 1001, 'key1': 10, 'key2': 10 }
我尝试了以下方法:
dict3 = {key: dict1[key] - dict2.get(key, 0) for key in ['key1', 'key2']}
但是我不知道如何保留原始的
'id'
因为您只有两个目录,而且元素很少,所以手动获取所需的目录要容易得多
>>> d3 = { 'id':dict1['id'] , 'key1':dict1['key1']-dict2['key1'] ,
'key2':dict1['key2']-dict2['key2'] }
>>> d3
=> {'id': 1001, 'key1': 10, 'key2': 10}
由于您只有两个dict
,元素很少,因此手动获取所需的dict
要容易得多
>>> d3 = { 'id':dict1['id'] , 'key1':dict1['key1']-dict2['key1'] ,
'key2':dict1['key2']-dict2['key2'] }
>>> d3
=> {'id': 1001, 'key1': 10, 'key2': 10}
您的代码很好,但我会使用dict comprehension
来更新dict,而不是创建它。这样,我就可以将它应用于一个已经用所需的'id'
值初始化的dict
dict1 = {'id': 1001, 'text': 'some text 1', 'key1': 11, 'key2': 12}
dict2 = {'id': 1002, 'text': 'some text 2', 'key1': 1, 'key2': 2}
dict3 = {'id': dict1['id']} # initialize it first
dict3.update({key: dict1[key] - dict2.get(key, 0) for key in ['key1', 'key2']})
print(dict3) # {'id': 1001, 'key1': 10, 'key2': 10}
您的代码很好,但我会使用dict comprehension
来更新dict,而不是创建它。这样,我就可以将它应用于一个已经用所需的'id'
值初始化的dict
dict1 = {'id': 1001, 'text': 'some text 1', 'key1': 11, 'key2': 12}
dict2 = {'id': 1002, 'text': 'some text 2', 'key1': 1, 'key2': 2}
dict3 = {'id': dict1['id']} # initialize it first
dict3.update({key: dict1[key] - dict2.get(key, 0) for key in ['key1', 'key2']})
print(dict3) # {'id': 1001, 'key1': 10, 'key2': 10}