Python:替换嵌套字典中的值
问题描述
只要键是'current_values',我想用与整数相同的值替换值(格式为字符串).
I want to replace the values (formated as strings) with the same values as integers, whenever the key is 'current_values'.
d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}
期望的输出:
d = {'id': '10', 'datastreams': [{'current_value': 5}, {'current_value': 4}]}
解决方案
d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}
for elem in d['datastreams']: # for each elem in the list datastreams
for k,v in elem.items(): # for key,val in the elem of the list
if 'current_value' in k: # if current_value is in the key
elem[k] = int(v) # Cast it to int
print(d)
输出:
{'id': '10', 'datastreams': [{'current_value': 5}, {'current_value': 4}]}
相关文章