Python:替换嵌套字典中的值 [英] Python: Replace values in nested dictionary

查看:65
本文介绍了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}]}

这篇关于Python:替换嵌套字典中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆