Python 3- Writing dictionaries with dictionary values to CSV files -


i've tried google- i've not been able find solution works dictionaries dictionary values. let me explain little simpler.

i have dictionary of ticket codes, , each ticket code dictionary, containing 'name' , 'redeemed'- name being ticket owner , redeemed being whether ticket has been redeemed. data loaded csv file named ticketcodes, contains 1000 lines of data. have system truncate file ready writing, solutions have found writing csv don't work. apologize if duplicate- may not have searched hard enough. if is, please can link me solution? thank much!

json better format writing out python dict data. however, if of dict's have same keys potentially format csv document dict key's column names.

for example:

# assuming data list of dictionaries the_data = [{'col1': 'data1', 'col2': 'data2'},             {'col1': 'data3', 'col2': 'data4'},             {'col1': 'data5', 'col2': 'data6'},             {'col1': 'data7', 'col2': 'data8'}]  # build list of column names. # done list(the_data[0].keys()) # have no control on column ordering column_names = ['col1', 'col2']  # print out column names print(",".join(column_names))  # print out data row in the_data:     print(",".join([row[field] field in column_names])) 

output:

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

note: in example have printed out csv data trivial write data file.

also, write the_data json format simple doing following:

>>> import json >>> json.dumps(the_data)  '[{"col2": "data2", "col1": "data1"}, {"col2": "data4", "col1": "data3"}, {"col2": "data6", "col1": "data5"}, {"col2": "data8", "col1": "data7"}]' 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -