-
-
Save toyeiei/582d5285be9b51d4ac8fe9c7690b4d32 to your computer and use it in GitHub Desktop.
Python tutorial - count items in a list, return a dict
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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