How to convert counter to dictionary in Python

In this article, We are going to learn “How to convert counter to the dictionary in Python“.

Introduction about Counter

Counter in Python gives special types of datasets provided by the Collections module.

It is used to count hashable objects.

from collections import Counter 
var=Counter("CodeSpeedy") 
print(var)

Output

Counter({'e': 3, 'd': 2, 'C': 1, 'o': 1, 'S': 1, 'p': 1, 'y': 1}).

We can see from the output that the counter object has created countable hashable objects. It created using the Ascending order of terms which are occurring maximum times.

Convert counter to dictionary in Python

The collections module has a variety of data structures like counter, OrderedDict, etc. We’ll be seeing Counter class in this article.

# Importing Module
from collections import Counter
# Creating Counter object
a=Counter({'a':5,'b':4,'c':3,'d':2,'e':1})
# Printing Counter a
print(a)

Output

Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

Here we have created an object of Counter by importing Counter from the collections module.

We are going to make a constructor of the dictionary so that using objects of the counter we can directly convert it into Dictionary.

# Creating dictionary b
# Here dict() constructor is used to make a new dictionary 
b=dict(a) 
## Printing Dictionary b 
print("Dictionary is ",b)

Output

Dictionary is {'e': 1, 'c': 3, 'b': 4, 'd': 2, 'a': 5}

I hope you found this article helpful to convert counter to the dictionary in Python.

Also read:

Leave a Reply