Reputation: 663
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
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
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