-3

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?

0

2 Answers 2

10

Use collections.Counter:

>>> from collections import Counter
>>> pet = ['cat','dog','fish','cat','fish','fish']
>>> Counter(pet)
Counter({'fish': 3, 'cat': 2, 'dog': 1})
Sign up to request clarification or add additional context in comments.

Comments

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}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.