[英]Slicing a python dictionary to perform operations
New 2.7 user. 新的2.7用户。 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: 我想从dict2中减去dict1中A的值以获得:
dict3 = {'val1': '5', 'val2': '15'}
Just create your dict using a dict comprehension: 只需使用dict理解即可创建dict:
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. for k, v in dict2.items()
在从所述dict2键/值对迭代然后我们访问来自dict1的“A”字典中的相应值与dict1["A"][k])
和减法。
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]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.