0

I have a list

list_1 = ['warning', 'media', 'media-other','media-other','warning-type2','threat','threat-type1]

I need to count the occurrence of different types as in the following dictionary

dict_1 = {'warning':0, 'media':0, 'threat':0}

I need to select similar types and increase the count. media and media-other should be counted as media. warning and warning-type2 should be counted as warning

The output of dict_1 after counting should be {'warning':2, 'media':3, 'threat':2}

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

2 Answers2

2

Assuming the part before any hyphen gives you the 'type' of the items in the list, you can use split and collections.Counter to count them:

from collections import Counter
Counter(word.split("-")[0] for word in list_1)
# returns  Counter({'warning': 2, 'media': 3, 'threat': 2})
Stuart
  • 9,597
  • 1
  • 21
  • 30
2
list_1 = ['warning', 'media', 'media-other','media-other','warning-type2','threat','threat-type1']

list_2 = [x.split('-')[0] for x in list_1]
dict_1 = {}
for key in list_2:
    if key not in dict_1.keys():
        dict_1[key] = list_2.count(key)
print(dict_1)