Jan Klaas
Jan Klaas

Reputation: 371

What's the correct way to loop over a list and make a dictionary with dict comprehension in python?

testWords is a list with words. setTestWords is the same list as a set. I want to create a dictionary with Dict Comprehension where I will use the word as key and the count as value. I'm also using the .count.

Example output would be like this:

>>> dictTestWordsCount[:2]
>>> {'hi': 22, 'hello': 99}

This is the line if code I'm using but it seems to crash my notebook every time.

l = {x: testWords.count(x) for x in setTestwords}

Upvotes: 1

Views: 51

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191743

Not sure what causes your notebook to crash...

In [62]: txt = "the quick red fox jumped over the lazy brown dog"

In [63]: testWords = txt.split()

In [64]: setTestWords = set(testWords)

In [65]: {x:testWords.count(x) for x in setTestWords}
Out[65]:
{'brown': 1,
 'dog': 1,
 'fox': 1,
 'jumped': 1,
 'lazy': 1,
 'over': 1,
 'quick': 1,
 'red': 1,
 'the': 2}

Or better, Use collection.defaultdict

from collections import defaultdict

d = defaultdict(int)

for word in txt.split():
    d[word]+=1

print(d)
defaultdict(int,
            {'brown': 1,
             'dog': 1,
             'fox': 1,
             'jumped': 1,
             'lazy': 1,
             'over': 1,
             'quick': 1,
             'red': 1,
             'the': 2})

Upvotes: 2

Related Questions