如何在列表中搜索字典键 [英] How to search for the dictionary keys in a list

查看:76
本文介绍了如何在列表中搜索字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个字典:

lst = {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5, 'elections': 5}

我有一个清单:

mylist = [['a new', 'party'], ['to', 'lol'], ['compete'], ['in', 'adore', 'the 2013'], ['federal', 'elections'], ['The Free', 'Voters'], ['leadership', 'declined to'], ['join forces', 'according to', 'a leaked'], ['email from', 'Bernd Lucke'], ['Advocating', 'adore'] ]

我希望能够在列表中搜索字典中的键.如果列表中的一个单词是一个键,则取该键的值并将其添加到计数器中.最后,要获得所有值的总和.

I want to be able to search the list for the keys in the dictionary. If a word in the list is a key, then to take the value of that key and add it to a counter. In the end, to have a total sum of all the values.

有没有办法做到这一点?

Is there a way to do this?

推荐答案

喜欢吗?

lst = {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5, 'elections': 5}
mylist = [['a new', 'party'], ['to', 'lol'], ['compete'], ['in', 'adore', 'the 2013'], ['federal', 'elections'], ['The Free', 'Voters'], ['leadership', 'declined to'], ['join forces', 'according to', 'a leaked'], ['email from', 'Bernd Lucke'], ['Advocating', 'adore']]

print([lst.get(i) for j in mylist for i in j if lst.get(i) != None])
print(sum([lst.get(i) for j in mylist for i in j if lst.get(i) != None]))

输出:

[10, 5, 10]
25


如果您在一行中不喜欢它们:


If you don't like them in one line:

total = []

for i in mylist:
    for j in i:
        if lst.get(i) != None:
            total.append(lst.get(i))

print(sum(total))

这篇关于如何在列表中搜索字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆