Counting the Number of keywords in a dictionary in python

前端 未结 5 1562
离开以前
离开以前 2020-12-04 08:11

I have a list of words in a dictionary with the value = the repetition of the keyword but I only want a list of distinct words so I wanted to count the number of keywords. I

5条回答
  •  盖世英雄少女心
    2020-12-04 08:44

    If the question is about counting the number of keywords then would recommend something like

    def countoccurrences(store, value):
        try:
            store[value] = store[value] + 1
        except KeyError as e:
            store[value] = 1
        return
    

    in the main function have something that loops through the data and pass the values to countoccurrences function

    if __name__ == "__main__":
        store = {}
        list = ('a', 'a', 'b', 'c', 'c')
        for data in list:
            countoccurrences(store, data)
        for k, v in store.iteritems():
            print "Key " + k + " has occurred "  + str(v) + " times"
    

    The code outputs

    Key a has occurred 2 times
    Key c has occurred 2 times
    Key b has occurred 1 times
    

提交回复
热议问题