counter() function in python by R4R Team

- Counter() is a python function defined in collections module that are used to convert the list into the dictionary according to the occurence of the item in the list.
-Number of key in dictionary is equal to the number of distinct elements in list.

Syntax-

collections.Counter(seq)

-It return the dictionary of python.

Example-

list is =['a','a','b','a','c','c']
then collections.Counter(list) will return {'a':3,'b':1,'c':2}


program-

#import the collections module
import collections

#input of the list
print("Enter item in list")
list=input().split()

print("nList is :",list)

dict=collections.Counter(list)
print("Dictionary is :",dict)


output-

Enter item in list
a b a b a c c c c b d a
List is : ['a', 'b', 'a', 'b', 'a', 'c', 'c', 'c', 'c', 'b', 'd', 'a']
Dictionary is : Counter({'a': 4, 'c': 4, 'b': 3, 'd': 1})


-In this program, we take an input of the list, then for each distinct value in list we make the key of the dictionary, then occurrence of item in list is become the value in dictionary.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!