Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python counting occurrences value in nested dictionary

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

print(count(data, 'Online'))

I want the result to be 2.

>Solution :

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"
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading