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
相关产品推荐
相关产品推荐

