簡體   English   中英

如何遍歷字典中每個鍵具有多個值的值

[英]How to iterate over values in dictionary which each key has multiple values

我有一本這樣的字典:

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

使用內置函數sum() ,並傳遞一個適當的生成器表達式: sum(k for k,v in d.items() if 'technology' in v) (nb在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

參考文獻:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM