+1 vote
in Programming Languages by (71.8k points)
I want to count the frequency of all elements in a list using a dictionary. How can I do it?

1 Answer

+2 votes
by (353k points)
selected by
 
Best answer

You need to create a dictionary with each element of the list as keys and their frequency as values. Then you can find the frequency of any element by accessing its value.

Here is an example:

>>> aa=[1, 2, 3, 2, 1, 3, 1, 2, 3, 3]
>>> freq={}
>>> for v in aa:
...     freq[v]=freq.get(v,0)+1
...
>>> freq
{1: 3, 2: 3, 3: 4}

Now you can find the frequency of any element using the dictionary 'freq'.


...