I have the following list:
pet = ['cat','dog','fish','cat','fish','fish']
and I need to convert it to a dictionary like this:
number_pets= {'cat':2, 'dog':1, 'fish':3}
How do I do it?
I have the following list:
pet = ['cat','dog','fish','cat','fish','fish']
and I need to convert it to a dictionary like this:
number_pets= {'cat':2, 'dog':1, 'fish':3}
How do I do it?
Use collections.Counter
:
>>> from collections import Counter
>>> pet = ['cat','dog','fish','cat','fish','fish']
>>> Counter(pet)
Counter({'fish': 3, 'cat': 2, 'dog': 1})
As @hcwhsa said, you can use collections.Counter
. But if you want to write your own class, you can start with something like this:
class Counter(object):
def __init__(self, list):
self.list = list
def count(self):
output = {}
for each in self.list:
if not each in output:
output[each] = 0
output[each]+=1
return output
>>> Counter(['cat', 'dog', 'fish', 'cat', 'fish', 'fish']).count()
>>> {'fish': 3, 'dog': 1, 'cat': 2}