Search code examples
pythonlist-comprehensionword-count

How to count words by grouping similar words in Python?


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}


Solution

  • 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)