简体   繁体   中英

Python 3- Writing dictionaries with dictionary values to CSV files

I've tried google- but I've not been able to find a solution that works with dictionaries with dictionary values. Let me explain a little simpler.

I have a dictionary of Ticket Codes, and with each ticket code is another dictionary, containing 'name' and 'redeemed'- name being the ticket owner and redeemed being whether the ticket has been redeemed. The data is loaded from a csv file named TicketCodes, which contains 1000 lines of this data. I have a system that will truncate the file ready for writing, but the solutions I have found for writing to a CSV don't work. I apologize if this is a duplicate- I may not have searched hard enough. If it is, please can you link me to a solution? Thank you very much!

JSON would be a much better format for writing out Python dict data. However, if all of your dict's have the same keys then you could potentially format a CSV document with the dict key's as the column names.

For example:

# Assuming the data is a list of dictionaries
the_data = [{'col1': 'data1', 'col2': 'data2'},
            {'col1': 'data3', 'col2': 'data4'},
            {'col1': 'data5', 'col2': 'data6'},
            {'col1': 'data7', 'col2': 'data8'}]

# Build a list of the column names.
# This could be done with list(the_data[0].keys())
# But then you have no control over the column ordering
column_names = ['col1', 'col2']

# Print out column names
print(",".join(column_names))

# Print out data
for row in the_data:
    print(",".join([row[field] for field in column_names]))

Output:

col1,col2
data1,data2
data3,data4
data5,data6
data7,data8

Note: In my example I have just printed out the CSV data but it would be trivial to write this data to a file.

Also, to write the_data to JSON format it is as simple as doing the following:

>>> import json
>>> json.dumps(the_data)

'[{"col2": "data2", "col1": "data1"}, {"col2": "data4", "col1": "data3"}, {"col2": "data6", "col1": "data5"}, {"col2": "data8", "col1": "data7"}]'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM