Caroline.py Caroline.py - 2 months ago 17
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

Just create your dict using a dict comprehension:

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

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.

Comments