gpt4 book ai didi

python - 有条件地计算嵌套 python json 字典中值的数量

转载 作者:行者123 更新时间:2023-12-01 06:55:48 25 4
gpt4 key购买 nike

我有一个 json 响应对象我想计算 state=healthy

出现的次数
d= {
"ResponseMetadata": {
"HTTPHeaders": {
"content-length": "444",
"content-type": "text/xml",
"date": "Tue, 12 Nov 2019 02:30:11 GMT",
"x-amzn-requestid": "1234"
},
"HTTPStatusCode": 200,
"RequestId": "1234",
"RetryAttempts": 0
},
"TargetHealthDescriptions": [
{
"HealthCheckPort": "80",
"Target": {
"Id": "i-dummy",
"Port": 80
},
"TargetHealth": {
"State": "healthy"
}
},
{
"HealthCheckPort": "80",
"Target": {
"Id": "i-testing",
"Port": 80
},
"TargetHealth": {
"State": "healthy"
}
}
]
}

我尝试过:

count = 0
for x,y in d.items():
if y['State'] == 'healthy':
count += 1
print(count)

但它提示

Traceback (most recent call last):
File "deploy_staging_web.py", line , in <module>
if y['State'] == 'healthy':
TypeError: list indices must be integers, not str

我该如何解决这个问题?

最佳答案

您可以使用递归:

def get_sum(d):
val = 0 if not isinstance(d, dict) else d.get('State') == 'healthy'
return val+sum(get_sum(i) for i in getattr(d, 'values', lambda :d)() if isinstance(i, (dict, list)))

print(get_sum(d))

输出:

2

关于python - 有条件地计算嵌套 python json 字典中值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58811324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com