Steveatron1
Steveatron1

Reputation: 3

Writing list of dictionaries to CSV with each dictionary's values in a new column

Forgive me. I'm very new to Python.

I have a list of dictionaries that I would like to write to an Excel spreadsheet. I know exactly how many keys each dictionary will contain and each dictionary will have the same keys. I would like to get the keys in column A and their values in columns B through however many dictionaries I have. My code so far:

for each in stock_data:
    with open('output.csv', 'wb') as output:
        writer = csv.writer(output)
        for key, value in each.iteritems():
            writer.writerow([key, value])

However, each iteration overwrites the previous one. Thanks in advance for your help.

Edit: with the help of those that took the time to answer, I ended up with this (the values of the dictionaries were tuples):

with open('output.csv', 'wb') as output:
fieldnames = ['Volume', 'Symbol', 'Adj_Close', 'High', 'Low', 'Date', 'Close', 'Open']
writer = csv.DictWriter(output, fieldnames=fieldnames)
writer.writeheader()
writer = csv.writer(output)

for each in stock_data:
    temp_list = []
    for value in each.iteritems():
        value = list(value)
        temp_list.append(value[1])

    writer.writerow(temp_list)

Upvotes: 0

Views: 3862

Answers (3)

Chinmay Kanchi
Chinmay Kanchi

Reputation: 66003

To solve your revised question - first make a list containing all your dicts

list_of_dicts = [{'a': 0.26677069056418323, 'b': 0.8343139335624713, 'c': 0.93725104506273127, 'd': 0.12143573904160743, 'e': 0.98963812790339856},
 {'a': 0.40332934706524204, 'b': 0.12289641894313152, 'c': 0.15252859039025357, 'd': 0.24458514688306432, 'e': 0.97469243562553942},
 {'a': 0.1878765127021168, 'b': 0.81273464692942443, 'c': 0.90229778310411091, 'd': 0.6172062385825835, 'e': 0.32644941601058663}]
for key in list_of_dicts[0]: #this iterates through all the keys
    #makes a row using the same key for each dict in the list
    row = [d[key] for d in list_of_dicts] 
    writer.writerow(row)

Alternatively, you could do this as a one-liner:

writer.writerows(([d[k] for d in list_of_dicts] for k in d))

Upvotes: 0

vzendara
vzendara

Reputation: 350

Your initial for loop opens the file with w each time, thereby overwriting the data. Trying using a for append.

Upvotes: 0

dting
dting

Reputation: 39287

You want to put your loop inside the open statement so you aren't closing and opening the file for each iteration:

with open('output.csv', 'wb') as output:
    writer = csv.writer(output)
    for each in stock_data:
        for key, value in each.iteritems():
            writer.writerow([key, value])

Upvotes: 3

Related Questions