只要键是'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}]}
这篇关于Python:替换嵌套字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!