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

时间:2017-11-10 17:58:29

标签: python dictionary

我有这样的字典:

{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行。

2 个答案:

答案 0 :(得分:4)

使用sum()内置函数,传递适当的生成器表达式:sum(k for k,v in d.items() if 'technology' in v)(n.b。在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

参考文献:

答案 1 :(得分:1)

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)