How to search dictionary keys in a list

Say I have a dictionary:

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

And I have a list:

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 for a list of keys in a dictionary. If the word in the list is a key, then take the value of this key and add it to the counter. In the end, to have a total sum of all values.

Is there any way to do this?

+1
source share
2 answers

Like 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]))

Output:

[10, 5, 10]
25

If you do not like them on one line:

total = []

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

print(sum(total))
+1
source

Perhaps you can do it in a more pythonic way.

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())
0
source

Source: https://habr.com/ru/post/1616713/


All Articles