man_ostrich
man_ostrich

Reputation: 23

Dictionary of element counts

I want to create a dictionary containing {x,list.count[x]}. However, I keep running into an error when trying to execute my code:

apple = ['variant', 'variant', 'variant2.0', 'variant 3.0']

pear = {}

for x in apple:
    pear.update({x,apple.count(x)})

The error is cannot convert dictionary update sequence element#0 to a sequence. Any suggestions?

Upvotes: 2

Views: 61

Answers (3)

Joe T. Boka
Joe T. Boka

Reputation: 6581

apple = ['variant', 'variant', 'variant2.0', 'variant 3.0']
pear = {}
for x in apple:
    pear[x] = pear.get(x, 0) +1
print (pear)

Output:

{'variant 3.0': 1, 'variant': 2, 'variant2.0': 1}

Upvotes: 1

weirdev
weirdev

Reputation: 1398

You have a syntax error in your dictionary definition. Try

pear.update({x : apple.count(x)})

Upvotes: 5

Aaron Hall
Aaron Hall

Reputation: 395893

May I suggest a collections.Counter:

>>> from collections import Counter
>>>
>>> apple = ['variant', 'variant', 'variant2.0', 'variant 3.0']
>>> Counter(apple)
Counter({'variant': 2, 'variant 3.0': 1, 'variant2.0': 1})

If you need it in a plain dict afterward:

>>> dict(Counter(apple))
{'variant 3.0': 1, 'variant': 2, 'variant2.0': 1}

Upvotes: 4

Related Questions