user1165419
user1165419

Reputation: 663

count elements in nested dict based on value (comprehension)

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?

Upvotes: 1

Views: 634

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95873

Yeah, but using a dictionary comprehension makes no sense:

>>> sum(1 for v in data.values() if v['sector1'] == 'finance')
2

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48057

You may use sum with generator expression as:

>>> sum(1 for data in my_data.values() if data['sector1'] == 'finance')
2

where my_data is holding the dict object mentioned in the question.

Upvotes: 1

Related Questions