Skip to content

Instantly share code, notes, and snippets.

@toyeiei
Created November 11, 2018 00:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toyeiei/582d5285be9b51d4ac8fe9c7690b4d32 to your computer and use it in GitHub Desktop.
Save toyeiei/582d5285be9b51d4ac8fe9c7690b4d32 to your computer and use it in GitHub Desktop.
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