Python:替换嵌套字典中的值

2024-05-16 09:49:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用与整数相同的值替换值(格式化为字符串),只要键是'当前值。在

d = {'id': '10', 'datastreams': [{'current_value': '5'}, {'current_value': '4'}]}

期望输出:

^{pr2}$

Tags: 字符串idvalue整数currentdatastreamspr2
3条回答

一般的方法(假设您事先不知道dict的哪个键指向一个列表)将遍历dict并检查其值的类型,然后根据需要再次迭代到每个值。在

在您的例子中,您的字典可能包含一个字典列表作为值,因此检查一个值是否属于list类型就足够了,如果是,则遍历该列表并更改所需的dict。在

可以使用如下函数递归完成:

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)

输出

^{pr2}$

可通过列表理解完成:

d['datastreams'] = [{'current_value': int(ds['current_value'])} if ('current_value' in ds) else ds for ds in d['datastreams']]

相关问题 更多 >