Home > Mobile >  Updating all keys of a nested dictionary from another dictionary (Python)
Updating all keys of a nested dictionary from another dictionary (Python)

Time:02-05

I have the following nested dictionary with around 1000 keys:

net_info = {
            '17052242':{'lengthkm': 1.555787, 'uparea': 123.23709555834532, 'order': 2,
                        'strmDrop_t': 231.5, 'unitarea': 123.23709555834532},
            '21009006':{'lengthkm': 6.677901703662528,'uparea': 493.8188826654188, 
                        'order': 2,'strmDrop_t': 5.3, 'unitarea': 36.89608111068623},
            .
            .
            .
             }

I would like to add a new "feature" called "Q" that I calculated using a predefined function that uses the value of the uparea that already exists inside the dictionary, is there a fast way to do this? I will be adding the Q for all the existing keys, there are no new keys.

An example of the function of the 'Q' would be:

def discharge(a):
    return 0.0229*pow(a,0.8781)

What I hope to obtain is:

net_info = {
            '17052242':{'lengthkm': 1.555787, 'uparea': 123.23709555834532, 'order': 2, 
                        'strmDrop_t': 231.5, 'unitarea': 123.23709555834532, 
                        'Q': 1.569334612348277},
            '21009006':{'lengthkm': 6.677901703662528,'uparea': 493.8188826654188, 
                        'order': 2, 'strmDrop_t': 5.3, 'unitarea': 36.89608111068623,
                        'Q': 5.309544598741915},
            .
            .
            .
             }

CodePudding user response:

You can just loop through your dict -

net_info = {
    '17052242': {'lengthkm': 1.555787, 'uparea': 123.23709555834532, 'order': 2,
                 'strmDrop_t': 231.5, 'unitarea': 123.23709555834532},
    '21009006': {'lengthkm': 6.677901703662528, 'uparea': 493.8188826654188,
                 'order': 2, 'strmDrop_t': 5.3, 'unitarea': 36.89608111068623}
}


def discharge(a):
    return 0.0229*pow(a, 0.8781)


for k in net_info.keys():
    net_info[k]['Q'] = discharge(net_info[k]['uparea']) # beware if the `uparea` key is missing, use dict.get(key, default) instead.

print(net_info)

outputs -

{'17052242': {'lengthkm': 1.555787, 'uparea': 123.23709555834532, 'order': 2, 'strmDrop_t': 231.5, 'unitarea': 123.23709555834532, 'Q': 1.569334612348277}, '21009006': {'lengthkm': 6.677901703662528, 'uparea': 493.8188826654188, 'order': 2, 'strmDrop_t': 5.3, 'unitarea': 36.89608111068623, 'Q': 5.309544598741915}}

Note the newly added Q values in output.

CodePudding user response:

for x in net_info.values():
    x["Q"] = discharge(x["uparea"])

This changes each value inside net_info because they're dicts in a list - x is a reference to a dictionary, not a copy of it. If net_info was a list of simple types like int this wouldn't work.

  •  Tags:  
  • Related