Python dictionary count values
#Python dictionary count values by key items = ["Banana", "Apple", "Avocado", "Grapes", "Oranges", "Banana", "Apple", "Avocado", "Kiwi", "Pear"] #hash table object to hold the items and count counter = dict() #loop over each and increment by 1 for item in items: if item in counter.keys(): counter[item] += 1 else: counter[item] = 1 print(counter)
-------------------------------------------------------------------------------------------------------
#Output
{'Banana': 2, 'Apple': 2, 'Avocado': 2, 'Grapes': 1, 'Oranges': 1, 'Kiwi': 1, 'Pear': 1}
Comments
Post a Comment