2017-09-18 84 views
1

基本上,我提出了这个请求来高效地执行操作,但我猜我使用的数据结构不是。如果密钥存在,则从嵌套字典中减去字典值

首先字典:

f_dict = {'n1':{'x':1,'y':1,'z':3},'n2':{'x':6,'y':0, 'z':1}, ...} 
s_dict = {'x':3,'t':2, 'w':6, 'y':8, 'j':0, 'z':1} 

我想获得e这样的:

e = {'n1':{'x':-2,'y':-7,'z':1},'n2':{'x':3,'y':-8,'z':0}, ...} 
+0

请将您的示例更改为实际的python字典。 BTW,提示:x - 0 == x。你可以随时检查一个字典中的值,并给出一个默认的's_dict.get('a',0)'。 – pazqo

回答

0

你可以使用一个嵌套的字典理解和使用dict.get减去值或默认值(在此情况0):

>>> {key: {ikey: ival - s_dict.get(ikey, 0) 
...  for ikey, ival in i_dct.items()} 
... for key, i_dct in f_dict.items()} 
{'n1': {'x': -2, 'y': -7, 'z': 2}, 'n2': {'x': 3, 'y': -8, 'z': 0}} 

或者如果你更喜欢显式循环:

res = {} 
for key, i_dict in f_dict.items(): 
    newdct = {} 
    for ikey, ival in i_dict.items(): 
     newdct[ikey] = ival - s_dict.get(ikey, 0) 
    res[key] = newdct 

print(res) 
# {'n1': {'x': -2, 'y': -7, 'z': 2}, 'n2': {'x': 3, 'y': -8, 'z': 0}} 
+0

非常感谢,第二个代码片段正常工作! –

+0

@ J.Dillinger不客气。请不要忘记[接受](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)最有帮助的答案。 :) – MSeifert