Skip to content

Instantly share code, notes, and snippets.

@toyeiei
Created Nov 11, 2018
Embed
What would you like to do?
Python tutorial - count items in a list, return a dict
# input
animals = ['dog', 'cat', 'cat', 'dog', 'dog', 'dog', 'cat', 'dog', 'hippo']
# expected output
# result = {'dog':5, 'cat':3, 'hippo':1}
# create empty dict to save our output
result = {}
# we write for loop and if-else
# to check every item in the animals list
for animal in animals:
if animal in result:
result[animal] += 1
else:
result[animal] = 1
# print output
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment