def f(d):
for k,v in d.items():
if k == 'current_value':
d[k] = int(v)
elif type(v) is list:
for item in v:
if type(item) is dict:
f(item)
>>> d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}
>>> f(d)
>>> 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)
一般的方法(假设您事先不知道dict的哪个键指向一个列表)将遍历dict并检查其值的类型,然后根据需要再次迭代到每个值。在
在您的例子中,您的字典可能包含一个字典列表作为值,因此检查一个值是否属于list类型就足够了,如果是,则遍历该列表并更改所需的dict。在
可以使用如下函数递归完成:
输出:
^{pr2}$可通过列表理解完成:
相关问题 更多 >
编程相关推荐