如何在列表中搜索字典键

时间:2015-11-20 12:01:10

标签: python list loops search dictionary

说我有一本字典:

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'] ]

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

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:1)

喜欢这个吗?

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

如果你不喜欢他们在一行:

total = []

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

print(sum(total))

答案 1 :(得分:0)

可能你可以用更加pythonic的方式做到这一点。

lst = {'adore': 10, 'hate': 10, 'hello': 10, 'pigeon': 1, 'would': 5}
counter = {'adore': 0, 'hate': 0, 'hello': 0, 'pigeon': 0, 'would': 0}
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'] ]

def func():
    for key in lst.keys():
        for item in mylist:
            if key in item:
                counter[key] = counter[key] + lst[key]

func()
print sum(counter.values())