2017-09-18 99 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