gpt4 book ai didi

python - 嵌套字典 for 循环

转载 作者:行者123 更新时间:2023-12-04 02:35:39 24 4
gpt4 key购买 nike

我是编程新手。我试图弄清楚如何从“实际”中减去“预算”,然后使用嵌套 for 循环将值更新为“方差”。但是,我读到在迭代时更改字典并不是最佳做法。到目前为止,我一直对如何进行感到困惑。

for i in properties:
for j in properties[i]:
if j == "actual":
sum = properties[i][j]
print('\nActual:' , sum)
if j == "budgeted":
sum_two = properties[i][j]
print('Budgeted:' , sum_two)
diff = sum_two - sum
print('Variance:', diff)
default_value = 0

properties = {587: {'prop_name': 'Collington'}, 'rental_income': {'apartment_rent': '5120-0000', 'resident_assistance': '5121-0000', 'gain_loss': '5120-0000'}, 51200000: {'actual': 29620, 'budgeted': 30509, 'variance': default_value}, 51210000: {'actual': 25620, 'budgeted': 40509, 'variance': default_value}, ............

最佳答案

只需遍历字典并检查是否在内部字典中,actualvariancebudgeted 是否存在,如果存在则修改方差

for k, v in properties.items():
if (('actual' in v.keys()) and ('variance' in v.keys()) and ('budgeted' in v.keys())):
properties[k]['variance'] = properties[k]['actual']-properties[k]['budgeted']

关于python - 嵌套字典 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62033677/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com