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.
nested_list = [[hello, hello, hello, how, are, you],[1, 2, 2, 2],[tree, flower, tree]]
final_list = [{hello: 3, how: 1, are: 1, you: 1}, {1: 1, 2: 3}, {tree: 2, flower:1}]
dictionary = defaultdict(int)
for item in nested_list:
for x in item:
dictionary[x] += 1
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}]