在python中动态更改嵌套字典的值

时间:2019-08-01 14:29:30

标签: python list dictionary

我在嵌套字典python中有一个字典,想要动态更新。

我的字典格式

sample_control = {
    77000: {
        (5,100034): 1,   
        (5,100043): 1,                         
        (2,100014): 50.,  # target value
        (2,100020): 50.,  
        (2,100073): 0.,  
    }
}

目标值是动态计算的,我想更新字典中的目标值。

代码-

def calculateTarget():
     #some calculations 
     #target is calculated

每次计算新目标时如何更新字典

谢谢

1 个答案:

答案 0 :(得分:1)

通常,您可以使用任何返回值的函数/表达式来更新字典

例如,如果您想将顶级词典的键与嵌套字典的元组键中的第一项相乘,您可以执行以下操作:

sample_control = {
                77000: {
                            (5,100034): 1,   
                            (5,100043): 1,                         
                            (2,100014): 50.,  # target value
                            (2,100020): 50.,  
                            (2,100073): 0.,  
                        }
            }

def calculateTarget(a, b):
    return a * b

for key, nested_dict in sample_control.items():
    for nested_key in nested_dict:
        nested_dict[nested_key] = calculateTarget(key, nested_key[0])

给出:

{77000: {(5, 100034): 385000,
  (5, 100043): 385000,
  (2, 100014): 154000,
  (2, 100020): 154000,
  (2, 100073): 154000}}

您可能想要...?