Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Dictionary for loop

I'm new to programming. I'm trying to figure out how to subtract 'budgeted' from 'actual' and then update the value to 'variance' using a nested for loop. However, I've read that it isn't the best practice to change a dictionary while iterating. So far, I've been stumped on how to proceed.

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}, ............
like image 808
Barry L. Avatar asked Jul 29 '26 04:07

Barry L.


1 Answers

just iterate through the dictionary and check if in the inner dictionary, if actual, variance and budgeted exists or not, if yes then modify the variance value

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']
like image 114
sahasrara62 Avatar answered Jul 30 '26 16:07

sahasrara62



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!