2

Below is code that takes a list of dictionaries and writes them to a CSV file.

import csv

def createBaselineCSV(baselineDictionaryList, name):

    toCSV = baselineDictionaryList

    keys = toCSV[0].keys()
    print(keys)
    with open(name, 'w') as output_file:
        dict_writer = csv.DictWriter(output_file, fieldnames=keys)
        dict_writer.writeheader()
        dict_writer.writerows(toCSV)

contacts = [{'Name':'John Smith', 'Email':'[email protected]', 'Phone':'888-888-8888'}, {'Name':'Keith Stone', 'Email':'[email protected]', 'Phone':'000-000-000'}]

createBaselineCSV(contacts, 'contacts.csv')

However the columns of the created CSV file do not maintain a consistent format each time a new spreadsheet is created. So one time it might create a CSV that looks like:

Name, Email, Phone
John Smith, [email protected], 888-888-8888
Keith Stone, [email protected], 000-000-0000

And the next time it might make a CSV that looks like this:

Email, Phone, Name
[email protected], 888-888-8888, John Smith
[email protected], 000-000-0000, Keith Stone

Is there a good way to make sure that the CSV is created with the column cells in a fixed position each time? For example Column A is always 'Name', Column B is always 'Email', and Column C is always 'Phone'.

I am guessing that accomplishing this will mean calling createBaselineCSV on a different data type other than a list of dictionaries(because dictionaries don't maintain a specified order), rather than reformatting the code within the function. What would be the best approach?

1
  • 1
    Don't use the DictWriter, or use collections.OrderedDict if you must. Dictionaries are not intrinsically ordered: that matters. Commented Jun 30, 2017 at 6:22

2 Answers 2

4

Your problem is fieldnames=keys where keys comes from a dict which has no order. Just set fieldnames=['Name', 'Email', 'Phone'] or whatever you want it to be. You can continue using dicts and DictWriter.

Sign up to request clarification or add additional context in comments.

1 Comment

or use an OrderedDict
1

pandas makes this very easy:

import pandas as pd

contacts = [{'Name':'John Smith', 'Email':'[email protected]', 'Phone':'888-888-8888'}, {'Name':'Keith Stone', 'Email':'[email protected]', 'Phone':'000-000-000'}]
df = pd.DataFrame(contacts)
df[['Name', 'Email', 'Phone']].to_csv('contacts.csv', index=False)

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.