mercredi 8 février 2017

count elements in nested dict based on value (comprehension)

Vote count: 0

I've got a data structure like this;

{
"job3": {
    "sector1": "finance",
    "sector2": "it"
},
"job2": {
    "sector1": "finance",
    "sector2": "it"
},
"job1": {
    "sector1": "it",
    "sector2": "finance"
}

}

I am trying to figure out how I can count 'sector1' values that equate to 'finance'. The long way of doing this is;

count = 0

for x,y in data.items():
    if y['sector1'] == 'finance':
        count += 1

print(count)

But I am trying to see if it's possible to do it via dict comprehension using something like enumerate or len(), but have had no luck. Any suggestions/ideas or examples I can follow?

I'm using python 3, thanks.

asked 54 secs ago

Let's block ads! (Why?)



count elements in nested dict based on value (comprehension)

Aucun commentaire:

Enregistrer un commentaire