For this function,I want to count each elements' occurrences and return a dict. such as: [a,b,a,c,b,a,c] and return {a:3,b:2,c:2} How to do that?
You can use Counter then:
from collections import Counter
Counter( ['a','b','a','c','b','a','c'] )
Or DefaultDict:
from collections import defaultdict
d = defaultdict(int)
for x in lVals:
d[x] += 1
OR:
def get_cnt(lVals):
d = dict(zip(lVals, [0]*len(lVals)))
for x in lVals:
d[x] += 1
return d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With