In: Computer Science
PYTHON. Create a function that accepts a filename where in each line there is a name of a type of bird. use a python dictionary in order to count the # of time each bird appears. (1 line = 1 appearance) Loop over your dict. to print each species and the # of times it was seen in the file once all lines have been counted. return dictionary containing count
the filename opens this:
blackbird
canary
hummingbird
canary
hummingbird
canary
example of outcome. Blackbird,1
Hummingbird,2
Canary,3
Here is the code in python.
filename = input("Enter filename: ")
# reading all lines from the file and adding to a list
with open(filename,'r') as f:
all_lines = f.readlines()
for i in range(len(all_lines)):
# removing \n from the end each line in the list
all_lines[i] = all_lines[i].split("\n")[0]
# creating an empty dictionary
birdsCount = {}
# adding all birds to birdsCount if they are already not present
for bird in all_lines:
if bird not in birdsCount:
birdsCount[bird] = 0
# counting the occurence of each bird
for bird in all_lines:
birdsCount[bird]+=1
# printing the name of each bird and its count
for bird in birdsCount:
print("{},{}".format(bird,birdsCount[bird]))
I have added some comments to make you understand better
OUTPUT:
If you like the answer, please upvote.