Barry L.
Barry L.

Reputation: 33

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

Upvotes: 3

Views: 89

Answers (5)

bherbruck
bherbruck

Reputation: 2226

Your data is in a strange format, I always try to group like objects together in dictionaries rather than have metadata and "lists" of items in the same level of a dictionary. This will work for you though:

for prop in properties:
    p = properties[prop]
    if 'actual' or 'budgeted' in p.keys():
        # get() wont error if not found, also default to 0 if not found
        p['variance'] = p.get('budgeted', 0) - p.get('actual', 0)

import json
print(json.dumps(properties, indent=4))

Output:

{
    "587": {
        "prop_name": "Collington"
    },
    "rental_income": {
        "apartment_rent": "5120-0000",
        "resident_assistance": "5121-0000",
        "gain_loss": "5120-0000"
    },
    "51200000": {
        "actual": 29620,
        "budgeted": 30509,
        "variance": 889
    },
    "51210000": {
        "actual": 25620,
        "budgeted": 40509,
        "variance": 14889
    }
}

Upvotes: 1

Dallan
Dallan

Reputation: 516

Try something like:

for i in properties:
    properties[i]['variance'] = properties[i]['budgeted'] - properties[i]['actual']

If you aren't sure that bugeted and actual exist in the dictionaries, you should catch the KeyError and handle approprately:

for i in properties:
    try:
        properties[i]['variance'] = properties[i]['budgeted'] - properties[i]['actual']
    except KeyError:
        properties[i]['variance'] = -1 # Set to some special value or just pass

Upvotes: 1

sahasrara62
sahasrara62

Reputation: 11247

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']

Upvotes: 2

Ahmad Ali
Ahmad Ali

Reputation: 774

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

I didn't get what mean exactly, but this should work.

Upvotes: 0

orlp
orlp

Reputation: 117916

There is nothing wrong with modifying the values inside a dictionary while iterating. The only thing that is not recommend is modifying the dictionary itself, that is adding/removing elements.

Upvotes: 1

Related Questions