Search code examples
pythonlistdictionarynestedfrequency

How do I count the frequency of items for each nested list?


I have a list of lists and I would like to count the frequency of each item in each nested list. I tried using Defaultdict for the counting, but I don't know how to create a nice nested list of dictionaries as output to differ between the frequencies of each list in nested_list.

The list:

nested_list = [[hello, hello, hello, how, are, you],[1, 2, 2, 2],[tree, flower, tree]]

Desired output:

final_list = [{hello: 3, how: 1, are: 1, you: 1}, {1: 1, 2: 3}, {tree: 2, flower:1}]

What I currently have:

dictionary = defaultdict(int)

for item in nested_list: 
    for x in item:
        dictionary[x] += 1

Solution

  • Using collections.Counter, and converting to a dict:

    >>> from collections import Counter
    >>> [dict(Counter(x)) for x in nested_list]
    [{'hello': 3, 'how': 1, 'are': 1, 'you': 1},
     {1: 1, 2: 3},
     {'tree': 2, 'flower': 1}]