如何迭代字典中每个键都有多个值的值

2024-04-19 22:55:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本这样的字典:

{4722: "['children', 'dance', 'education','technology', 'teaching']",
3200: "['alternative energy', 'sustainability', 'technology']",
1636: "['computers', 'performance', 'simplicity', 'software', 'ice']",
1697: "['MacArthur grant', 'inequality', 'technology', 'pollution']"}

现在我想在每一行中找到“技术”这个词,并对键进行求和。就像这里我应该有4722+3200+1697的和。你知道吗

有人能帮我吗?你知道吗

我应该提到,我的原始数据帧有2000行。你知道吗


Tags: 字典performancesoftwareenergychildreneducationicealternative
2条回答
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)

使用sum()内置函数,传递适当的生成器表达式:sum(k for k,v in d.items() if 'technology' in v)(注意:在Python2中使用d.iteritems())。你知道吗

可运行演示:

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

参考文献:

相关问题 更多 >