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
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.
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.
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.
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.
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)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With