[Solved] How to count elements in a list and return a dict? [duplicate]


Using no external modules and only the count, although there would be some redundancy using dict comprehension:

d = {itm:L.count(itm) for itm in set(L)}

If you are allowed to use external modules and do not need to implement everything on your own, you could use Python’s defaultdict which is delivered through the collections module:

#!/usr/bin/env python3
# coding: utf-8

from collections import defaultdict

word_list = ['hello', 'hello', 'hi', 'hello', 'hello']

d = defaultdict(int)
for word in word_list:
    d[word] += 1

print(d.items())

Giving you:

dict_items([('hi', 1), ('hello', 4)])

EDIT:
As stated in the comments you could use a Counter like this, which would be easier:

#!/usr/bin/env python3
# coding: utf-8

from collections import Counter

word_list = ['hello', 'hello', 'hi', 'hello', 'hello']

c = Counter(word_list)

print(c)

Giving you:

Counter({'hello': 4, 'hi': 1})

5

solved How to count elements in a list and return a dict? [duplicate]