Ram K
Ram K

Reputation: 1785

Using counter to create dict of specifc words in the list

I have a list that looks like :

my_list = ['singapore','india','united states','london','paris','india','london','china','singapore','singapore','new york']

Now I want a Counter[dict] of only specific words in this list

Counter(my_list) gives me the following :
Counter({'singapore': 3, 'india': 2, 'london': 2, 'united states': 1, 'paris': 1, 'china': 1, 'new york': 1})

But is there a way to create a Counter of only specific words from a list , like for example Counter of words in ['london','india','singapore']

What would be the fastest way to do this ? My list is very large.

What I tried : my_list.count('london') for example. But is there a faster way to achieve this ?

Upvotes: 0

Views: 55

Answers (1)

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could use a set to filter the words, for example:

from collections import Counter

needles = {'london', 'india', 'singapore'}
haystack = ['singapore', 'india', 'united states', 'london', 'paris', 'india',
            'london', 'china', 'singapore', 'singapore', 'new york']

result = Counter(value for value in haystack if value in needles)
print(result)

Output

Counter({'singapore': 3, 'india': 2, 'london': 2})

Upvotes: 8

Related Questions