代码之家  ›  专栏  ›  技术社区  ›  J.Dillinger

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

  •  1
  • J.Dillinger  · 技术社区  · 7 年前

    第一条:

    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 回复  |  直到 7 年前
        1
  •  0
  •   MSeifert    7 年前

    dict.get

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