Yes, this is the whole thing that you either do not need or should not do. Here, as I would before Python 2.7 (after that, use collections.Counter, as shown in other answers). Keep in mind that this will return a dictionary containing the counts, not a print, you will have to do it from the outside. I would also not prefer to give a complete solution for homework, but it has already been done, so I believe that there is no real damage explaining this a bit.
def parseFile(filename): with open(filename, 'r') as fh: lines = fh.readlines() d={} for country in [line.split(',')[1].strip() for line in lines]: d[country] = d.get(country,0) + 1 return d
Let's break it down a bit, right?
with open(filename, 'r') as fh: lines = fh.readlines()
So you usually open a text file for reading. This will throw an IOError exception if the file does not exist or you do not have permissions or the like, so you want to catch it. readlines () reads the entire file and splits it into lines, each line becomes an element in the list.
d={}
It just initializes an empty dictionary
for country in [line.split(',')[1].strip() for line in lines]:
This is where the fun begins. A bracket enclosed to the right is called list comprehension, and it basically generates a list for you. What pretty much speaks plain English is βfor each element a line in the list lines, take this element / line, divide it by each comma, take the second element (index 1) of the list, which you get from the split , remove any spaces from it and use the result as an element in the new list "Then the left part of it only iterates over the generated list, indicating the name" country "on the current element in the body area of ββthe loop.
d[country] = d.get(country,0) + 1
Well, think about what happens if, instead of the specified line, we used the following:
d[country] = d[country] + 1
It will work correctly (exception KeyError), because d [country] does not matter the first time. Therefore, we use the get () method, all dictionaries have it. Here's the great part - get () takes an optional second argument, which we want to get from it if the element we are looking for does not exist. Therefore, instead of failing, it returns 0, which (unlike None), we can add 1 to and update the dictionary with a new counter. Then we just return it.
Hope this helps.