简体   繁体   中英

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?

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.

Yeah, but using a dictionary comprehension makes no sense:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM