How can I count the duplicate items present in a list of lists?

Viewed 118

I want to get the frequency of each item of every list in a list.

For example, given:

my_list = [['Wheels', 'Handle', 'Service'], 
          ['Wheels', 'Forks', 'Handle', 'Wheels', 'Service'],
          ['Motor Sensor', 'Motor Sensor', 'Electronic']]

I want to output the following:

[{'Wheels':1,'Handle':1,'Service':1},
 {'Wheels':2, 'Forks':1,'Handle':1,'Service':1},
 {'Motor Sensor':2,'Electronic':1}]
1 Answers

You can use collections.Counter() on each sublist, and then transform them to dictionaries.

from collections import Counter

my_list = [['Wheels', 'Handle', 'Service'], 
           ['Wheels', 'Forks', 'Handle', 'Wheels', 'Service'],
           ['Motor Sensor', 'Motor Sensor', 'Electronic']]
           
result = [dict(Counter(sublist)) for sublist in my_list]
print(result)
Related