Ank
Ank

Reputation: 6270

Python dictionary counting

I have a dictionary

a={}
a['A']=1
a['B']=1
a['C']=2

I need to output the following

1 has occurred 2 times
2 has occurred 1 times

What is the best way to do this.

Upvotes: 1

Views: 179

Answers (2)

Óscar López
Óscar López

Reputation: 236004

Use the Counter class:

from collections import Counter

a = {}
a["A"] = 1
a["B"] = 1
a["C"] = 2

c = Counter(a.values())

c
=> Counter({1: 2, 2: 1})

From the documentation:

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. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.

Upvotes: 1

Gareth Latty
Gareth Latty

Reputation: 89007

This is easily (and efficiently) done with collections.Counter(), which is designed to (unsurprisingly) count things:

>>> import collections
>>> a = {"A": 1, "B": 1, "C": 2}
>>> collections.Counter(a.values())
Counter({1: 2, 2: 1})

This gives you a dictionary-like object that can trivially be used to generate the output you want.

Upvotes: 6

Related Questions