Reputation: 334
I have a list, containing project names:
my_list = ['a', 'b', 'c', 'a', 'd', 'a', 'a']
I want to put the letters into a dictonary, with the key values containing the number, for how many time a letter is in a list:
my_dict = {'a' : 4, 'b' : 1, 'c' : 1, 'd' : 1}
How can I do this in python?
Upvotes: 0
Views: 60
Reputation: 473823
This is exactly what collections.Counter
is for:
A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.
>>> from collections import Counter
>>> my_list = ['a', 'b', 'c', 'a', 'd', 'a', 'a']
>>> Counter(my_list)
Counter({'a': 4, 'c': 1, 'b': 1, 'd': 1})
Upvotes: 5