[英]How to iterate over values in dictionary which each key has multiple values
I have a dictionary like this: 我有一本这样的字典:
{4722: "['children', 'dance', 'education','technology', 'teaching']",
3200: "['alternative energy', 'sustainability', 'technology']",
1636: "['computers', 'performance', 'simplicity', 'software', 'ice']",
1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"}
Now I want to find the word 'technology' in each row and sum the keys. 现在,我想在每一行中找到“技术”一词,并对键求和。 Like here I should have the sum of 4722 + 3200 + 1697 . 像这里一样,我的总和为4722 + 3200 + 1697。
Can anyone help me please? 谁能帮我吗?
I should mention that my original data frame has 2000 rows. 我应该提到我的原始数据框有2000行。
Use the sum()
built-in function, passing an appropriate generator expression: sum(k for k,v in d.items() if 'technology' in v)
(nb use d.iteritems()
in Python2). 使用内置函数sum()
,并传递一个适当的生成器表达式: sum(k for k,v in d.items() if 'technology' in v)
(nb在Python2中使用d.iteritems()
)。
Runnable demo: 可运行的演示:
d = {
4722: "['children', 'dance', 'education','technology', 'teaching']",
3200: "['alternative energy', 'sustainability', 'technology']",
1636: "['computers', 'performance', 'simplicity', 'software', 'ice']",
1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"
}
result = sum(k for k,v in d.items() if 'technology' in v)
assert result == 9619
References: 参考文献:
your_data = {
4722: "['children', 'dance', 'education','technology', 'teaching']",
3200: "['alternative energy', 'sustainability', 'technology']",
1636: "['computers', 'performance', 'simplicity', 'software', 'ice']",
1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"
}
sum_up = 0
for k, v in your_data.items():
if 'technology' in v:
sum_up += k
print('sum_up:', sum_up)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.