Question: Write a program country_convert.py that opens the included countryInfo.csv file and extracts the country name, capital city and population from each row, then writes a
Write a program country_convert.py that opens the included countryInfo.csv file and extracts the country name, capital city and population from each row, then writes a new file named country_simple_info.csv with country, capital and population in each row, with the rows sorted by population size, largest first.
Note this program does not take input/output file names, as it is specific to the file given. It only needs to run on the command line like this:
$ python country_convert.py
Which will result in a file named country_simple_info.csv whose first 4 lines are:
country,capital,population China,Beijing,1330044000 India,New Delhi,1173108018 United States,Washington,310232863 [...]
Hints: Dont try to do everything all together. There are several steps involved here, so break the problem down into steps that will have intermediate data before getting the final data. Built-in functions are your friends. Note column headings. You don't need intermediate files.
I suggest using DictReader to read the file. Read the whole file in at one time. Each element in the resulting list will be a dictionary of row data, containing the column name & cell value as the key, value pairs.
Then make a new list such that each element (namely, row) consists of a dictionary that only contains the values (columns) from the initial list that we want.
Now, you can make a new list of row data, in order, by using the built-in function sorted() . Look up the inputs to sorted() , since the values of the dictionary are only strings, not numbers. You may want to define a helper function.
Then write out the sorted list data with DictWriter .
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
