0

I'm trying to push multiple dictionaries (keys and values) to a csv file by matching the key to a column in the csv header. Example:

import csv
d1 = {'a':1, 'b':2, 'c': 3}
d2 = {'d':4, 'e':5, 'f': 6}
with open('my_data.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(['a', 'b', 'c', 'd', 'e', 'f'])

#iterate through all keys in d1,d2,dn
#if key matches column:
    #write value of key to the bottom of column
#else:
    #error key not found in header

expected result in mydata.csv

a,b,c,d,e,f
1,2,3,4,5,6
1
  • Not sure I get it. Are you merging all the dicts into a single line in the output file (as shown)? Or do you want each input dict to be a line in the output file? Commented Oct 28, 2015 at 21:54

1 Answer 1

1

The answer is.. don't just pass the column names to writerow().. put them in a variable columns and then use that to control the order in which the values are written out. Python dictionaries have no order.. you have to use a little bit of code to sort the values into the order you want.

The last line of code, which writes out the values into the CSV, uses a python feature called List Comprehension. It's a shortcut that saves 3-4 lines of code. Look it up, they are very handy.

import csv
d1 = {'a':1, 'b':2, 'c': 3}
d2 = {'d':4, 'e':5, 'f': 6}

columns = ['a', 'b', 'c', 'd', 'e', 'f']

# combine d1 and d2 into data.. there are other ways but this is easy to understand
data = dict(d1)
data.update(d2)

with open('my_data.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(columns)
    # make a list of values in the order of columns and write them
    w.writerow([data.get(col, None) for col in columns])

Here is what it would look like without the list comprehension:

    row = []
    for col in columns:
        row.append(data.get(col, None)) 
    w.writerow(row)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.