You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何统计嵌套字典中指定值的出现次数

嵌套字典指定值统计实现方案

你可以直接修改原有递归逻辑,遍历所有字典值做匹配即可,实现代码如下:

def count_value(d, target):
    cnt = 0
    for val in d.values():
        if val == target:
            cnt += 1
        # 嵌套字典递归统计
        if isinstance(val, dict):
            cnt += count_value(val, target)
    return cnt

调用示例:
print(count_value(data, 'Online'))
输出结果为 2,符合预期。


注意事项

你给出的示例data存在语法错误,修正后可直接测试上述函数,正确的data结构如下:

data = {"members": {
    "1": {
        "name": "burek",            
        "status": {
            "description": "Online",
            "state": "Busy",
            "color": "green",
        },
        "position": "seller"
    },
    "2": {
        "name": "pica",         
        "status": {
            "description": "Offline",
            "state": "Idle",
            "color": "red",
        },
        "position": "waiting"
    },
    "3": {
        "name": "strucko",          
        "status": {
            "description": "Online",
            "state": "Busy",
            "color": "green",
        },
        "position": "backside"
    }
}}

如果后续需要适配包含列表的嵌套结构,补充列表遍历逻辑即可。


内容的提问来源于stack exchange,提问作者Rock Son

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:45:07