Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract dictionary from Counter object

I want to count the number of times a word occur in a list of sting.

['this is a red ball','this is another red ball']

I wrote the following code

counts = Counter()
for sentence in lines:
    counts.update(word.strip('.,?!"\'').lower() for word in sentence.split())

It gives me a result in the following format

Counter({'': 6, 'red': 2, 'this': 2, ....})

How can I only get the dictionary?

like image 710
akira Avatar asked Sep 26 '15 11:09

akira


People also ask

How to convert a dictionary to dictionary using objects of counter?

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)

Is it possible to use a counter in a Python dictionary?

Though you will have all the operations in countsvariable which you can do in a normal python dictionary because Counteris a subclass of dict. From Counterdocs:

What is a counter class in Python?

Python | Counter Objects | elements() Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general purpose built-ins like dictionaries, lists and tuples.

How do you get the value of a counter in Python?

Once a Counter is populated, its values can be retrieved using the dictionary API. Counter does not raise KeyError for unknown items. its count is 0. For Python training, our top recommendation is DataCamp. times as its count. Elements are returned in arbitrary order.


1 Answers

You can just do the following if a dictionary is really what you want.

dict(counts)

Though you will have all the operations in counts variable which you can do in a normal python dictionary because Counter is a subclass of dict.

From Counter docs:

A Counter is a dict subclass for counting hashable objects.

like image 172
Rahul Gupta Avatar answered Oct 01 '22 15:10

Rahul Gupta