Zy Taga
Zy Taga

Reputation: 89

Simple dictionary comprehension

Check me out on this

languages = ['English', 'German', 'English', 'Italian', 'Italian', 'English', 'German', 'French']

I want to generate a frequency table out of it. So I did

freq = {}
for language in languages:
    if language in freq:
        freq[language] += 1
    else:
        freq[language] = 1

Which is correct

BUT I want to use count() wihthin a dictionary comprehension to solve it. I got it wrong for several tries.

Upvotes: 1

Views: 55

Answers (3)

U13-Forward
U13-Forward

Reputation: 71610

Since you mentioned "dictionary comprehension", you could try:

>>> {k: languages.count(k) for k in dict.fromkeys(languages)}
{'English': 3, 'German': 2, 'Italian': 2, 'French': 1}
>>>

Or just:

>>> {k: languages.count(k) for k in languages}
{'English': 3, 'German': 2, 'Italian': 2, 'French': 1}
>>>

Or without dictionary comprehension you could try dict(zip(...)) with map(...):

>>> dict(zip(languages, map(languages.count, languages)))
{'English': 3, 'German': 2, 'Italian': 2, 'French': 1}
>>> 
 

Or just collections.Counter:

>>> from collections import Counter
>>> Counter(languages)
Counter({'English': 3, 'German': 2, 'Italian': 2, 'French': 1})
>>> 

Upvotes: 1

hd1
hd1

Reputation: 34677

I would use the Counter class for this:

from collections import Counter
freq = Counter(languages)

Now freq will contain your languages in descending order of their occurrence in the languages list.

Upvotes: 0

Osman Mamun
Osman Mamun

Reputation: 2882

Use Counter from collections:

In [1]: from collections import Counter

In [2]: languages = ['English', 'German', 'English', 'Italian', 'Italian', 'English', 'Ger
   ...: man', 'French']

In [3]: count = Counter(languages)

In [4]: count
Out[4]: Counter({'English': 3, 'German': 2, 'Italian': 2, 'French': 1})

Upvotes: 6

Related Questions