Skip to content

Instantly share code, notes, and snippets.

Created Nov 11, 2018
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
result[animal] = 1
# print output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment