Counter in Python

A counter is a container that holds elements as dictionary keys and their counts as dictionary values.

Let’s understand the concept through programming

from collections import Counternums=[1,2,3,1,4,5,1]counter=Counter(nums)print(counter) #o/p=Counter({1: 3, 2: 1, 3: 1, 4: 1, 5: 1})print(counter.keys()) #o/p=dict_keys([1, 2, 3, 4, 5])print(counter.values()) #o/p=dict_values([3, 1, 1, 1, 1])## One difference between normal python dict and Counter is## for missing elements it return zero count but dict object raise a KeyErrorprint(counter[80]) ## o/p=0 You can see key 80 is not found in counter

Note: Please feel free to comment if you find any errors. Also, you can suggest if you want me to improve this blog.

If you like this please hit the clap. You can even clap as many times as you want. Please check it if you can clap more than once.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store