简体   繁体   中英

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

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.

If I understood your problem correctly, this should work :

# dict1 and dict2 have been initialized
dict3 = {}
for key in dict2:
    dict3[key] = str(int(dict2[key])-int(dict1["A"][key]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM