I am stuck with unable to find a solution to count value.
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"
}}
Now I can count the keys:
def count(d, k):
return (k in d) sum(count(v, k) for v in d.values() if isinstance(v, dict))
But have a lot of trouble figuring out ways to count the value.
print(count(data, 'Online'))
I want the result to be 2.
CodePudding user response:
One approach:
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)
Output
2
Setup
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"
}
}
}