Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用setten键理解新词典_Python_Python 2.7_Dictionary_Dictionary Comprehension - Fatal编程技术网

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}