[英]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'. 我试图弄清楚如何计算等于“财务”的“ sector1”值。 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. 但是我试图看看是否有可能通过使用诸如枚举或len()之类的dict理解来做到这一点,但是没有运气。 Any suggestions/ideas or examples I can follow?
我可以遵循的任何建议/想法或示例吗?
You may use sum
with generator expression as: 您可以将
sum
与生成器表达式一起使用:
>>> 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. 其中
my_data
保存问题中提到的dict
对象。
Yeah, but using a dictionary comprehension makes no sense: 是的,但是使用字典理解毫无意义:
>>> sum(1 for v in data.values() if v['sector1'] == 'finance')
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.