Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to turn word list into frequency dict

Tags:

What's the best way to convert a list/tuple into a dict where the keys are the distinct values of the list and the values are the the frequencies of those distinct values?

In other words:

['a', 'b', 'b', 'a', 'b', 'c'] -->  {'a': 2, 'b': 3, 'c': 1} 

(I've had to do something like the above so many times, is there anything in the standard lib that does it for you?)

EDIT:

Jacob Gabrielson points out there is something coming in the standard lib for the 2.7/3.1 branch

like image 692
ʞɔıu Avatar asked Apr 06 '09 18:04

ʞɔıu


People also ask

How do you find the frequency of a word in Python?

Use set() method to remove a duplicate and to give a set of unique words. Iterate over the set and use count function (i.e. string. count(newstring[iteration])) to find the frequency of word at each iteration.

How do you find the frequency of a list?

We can use the counter() method from the collections module to count the frequency of elements in a list. The counter() method takes an iterable object as an input argument. It returns a Counter object which stores the frequency of all the elements in the form of key-value pairs.

Can dict list have value?

It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.

Can you turn a list into a dictionary?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.


1 Answers

I find that the easiest to understand (while might not be the most efficient) way is to do:

{i:words.count(i) for i in set(words)} 
like image 94
SilentGhost Avatar answered Sep 21 '22 13:09

SilentGhost