如果密钥存在,则从嵌套字典中减去dict值

时间:2017-09-18 15:00:51

标签: python dictionary subtraction

基本上我提出了有效执行操作的请求,但我想我使用的数据结构并非如此。

第一个词:

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}, ...} 

1 个答案:

答案 0 :(得分: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}}