简体   繁体   English

如果键存在,则从嵌套字典中减去字典值

[英]Subtract dict value from a nested dict if the key exists

Basically I made this request to perform the operation efficiently but I guess the data structure I'm using isn't. 基本上,我发出此请求是为了有效地执行操作,但是我想我使用的数据结构不是。

First dict: 第一个字典:

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}

I want to obtain e such that: 我想获得e使得:

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

You could use a nested dictionary comprehension and use dict.get to subtract the value or a default value (in this case 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}}

Or if you prefer explicit loops: 或者,如果您喜欢显式循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM