python 计算嵌套字典中出现的值
python counting occurrences value in nested dictionary
我无法找到计算值的解决方案。
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"
}}
现在我可以数钥匙了:
def count(d, k):
return (k in d) + sum(count(v, k) for v in d.values() if isinstance(v, dict))
但是在想出计算值的方法时遇到了很多麻烦。
print(count(data, 'Online'))
我希望结果为 2。
一种方法:
def count(d, k):
current = 0
for di in d.values():
if isinstance(di, dict):
current += count(di, k)
elif k == di:
current += 1
return current
res = count(data, "Online")
print(res)
输出
2
设置
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"
}
}
}
我无法找到计算值的解决方案。
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"
}}
现在我可以数钥匙了:
def count(d, k):
return (k in d) + sum(count(v, k) for v in d.values() if isinstance(v, dict))
但是在想出计算值的方法时遇到了很多麻烦。
print(count(data, 'Online'))
我希望结果为 2。
一种方法:
def count(d, k):
current = 0
for di in d.values():
if isinstance(di, dict):
current += count(di, k)
elif k == di:
current += 1
return current
res = count(data, "Online")
print(res)
输出
2
设置
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"
}
}
}