'Writing output csv file python

I'm trying to write a list into a csv file so that it's properly formatted. I've read from other stack overflow posts that below is the correct way to do so, (in order to preserve commas that I want to be printed out, etc), but this is just not working for me.

Rather than printing every list (within final_list) in its own csv row, it just prints one list per cell in one long, continuous line aka no line breaks. Any ideas on what I can do?

import csv 

final_list = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']

for key, value in sorted(stats_dict.iteritems()):
    if value[5] != 0:
        final_list.append([key, value[4], value[5], value[0], value[1]])

with open("output.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerow(final_list)


Solution 1:[1]

I think you might be on Python 2.x but maybe this will help. I filled in a dummy stats_dict and rearranged the index of values (I call them v). I also made your final_list a list of lists.

final_list = [['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']]
stats_dict = {'Key': ['USA', 250000000, 75, 1000000, 1000001]}
for k, v in sorted(stats_dict.items()):
    if v[4] != 0:
        final_list.append([v[0], v[1], v[2], v[3], v[4]])

with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerows(final_list)

Solution 2:[2]

Your code is almost spot on. You just need to see the difference between how final_list is evaluated in these two lines:

final_list = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']

and...

final_list.append([key, value[4], value[5], value[0], value[1]])

The first is a list of strings, the second is a list of lists. The second one is correct - each row in your CSV file is expected to be a list. To correct your code, make your first (header) row a list as well:

import csv 

# note that we have really only changed the next line
final_list = [['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']]

for key, value in sorted(stats_dict.iteritems()):
    if value[5] != 0:
        final_list.append([key, value[4], value[5], value[0], value[1]])

with open("output.csv", "w") as f:
    writer = csv.writer(f)
    writer.writerows(final_list) # we use writerows not writerow

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jarad
Solution 2