-4

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?

mwil.me
  • 1,134
  • 1
  • 19
  • 33

2 Answers2

10

Use collections.Counter:

>>> from collections import Counter
>>> pet = ['cat','dog','fish','cat','fish','fish']
>>> Counter(pet)
Counter({'fish': 3, 'cat': 2, 'dog': 1})
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

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}
JadedTuna
  • 1,783
  • 2
  • 18
  • 32