- 1 year ago 124
Python Question

Slicing a python dictionary to perform operations

New 2.7 user. I have the following dictionary:

dict1 = {'A': {'val1': '5', 'val2': '1'},
'B': {'val1': '10', 'val2': '10'},
'C': {'val1': '15', 'val3': '100'}}

I have another dictionary

dict2 = {'val1': '10', 'val2': '16'}

I want to subtract the values from A in dict1 from dict2 to get:

dict3 = {'val1': '5', 'val2': '15'}

Answer Source

Just create your dict using a dict comprehension:

d3 = {k: str(int(v) - int(dict1["A"][k])) for k, v in dict2.items()}

Which would give you:

 {'val2': '15', 'val1': '5'}

for k, v in dict2.items() iterates over the key/value pairs from dict2 then we access the corresponding value from dict1's "A" dict with dict1["A"][k]) and subtract.

If you plan on doing calculations like that you may be as well to store the values as actual ints, not strings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download