0

I am trying to add elements and their count in a list to a dictionary, but getting Type Error. Here is my code :

v= ["a","b","c","b","a"]

res= {}
for i in set(v):
    res.update( i = v.count[i] )
print(res)

The error I am getting is:

TypeError: 'builtin_function_or_method' object is not subscriptable

Mureinik
  • 277,661
  • 50
  • 283
  • 320
CompletelyLost
  • 45
  • 1
  • 12

1 Answers1

2

You don't need to reinvent the wheel - you can use Python's Counter:

from collections import Counter
v = ["a","b","c","b","a"]
result = Counter(v)

And if you absolutely need a dictionary and not just an object that can act like one:

result = dict(Counter(v))
Mureinik
  • 277,661
  • 50
  • 283
  • 320