In: Computer Science
{PYTHON }You have a CSV file containing the
location and population of various cities around the world. For
this question you'll be given a list of cities and return the total
population across all those cities.
Write a function named "total_population" that takes a string then
a list as parameters where the string represents the name of a CSV
file containing city data in the format
"CountryCode,CityName,Region,Population,Latitude,Longitude" and the
second parameter is a list where each element is itself a list
containing 3 strings as elements representing the CountryCode,
CityName, and Region in this order. Return the total population of
all cities in the list. Note that the city must match the country,
name, and region to ensure that the correct city is being read.
import pandas as pd #to read csv into a dataset
def total_population(file_name, city_list): #function definition with required parameters
data = pd.read_csv(file_name) #reading a csv file
pop = 0 #for storing population
for i in city_list: #looping through the list
temp = data.loc[(data.CountryCode == int(i[0])) & (data.CityName == i[1]) & (data.Region == i[2])] #selecting row matching the conditions
pop += int(temp['Population']) #summing population for each city
return pop #returning total population
#sample test run
print('Total Population =',total_population('hello.csv', [['013','Mumbai','West'],['014','Dun','North']]))
Screenshot of output: