I have a list of tuples in the form:
data = [({1: 0.1723, 2: 0.890, 3: 1.0}, 'a'),
({1: 0.0, 2: 1.0, 3: 0.667}, 'b'),
({1: 0.223, 2: 0.336, 3: 1.0}, 'b')]
The second element of each tuple is simply a string.
How can I write it to a csv file so that the contiguous columns correspond to each element?
ie: for data[1]
: col1 = 0.1723
, col2 = 0.890
, col3 = 1.0
, col4 = 'a'
?
You could use a generator expression to generate all rows at once, which come in 2 parts.
this code:
import csv
data = [({1: 0.1723, 2: 0.890, 3: 1.0}, 'a'),
({1: 0.0, 2: 1.0, 3: 0.667}, 'b'),
({1: 0.223, 2: 0.336, 3: 1.0}, 'b')]
with open("output.csv","w",newline="") as f: # python 2: just: ,"wb")
cw = csv.writer(f)
cw.writerows([v for _,v in sorted(d.items())] + [s] for d,s in data)
creates the following file:
0.1723,0.89,1.0,a
0.0,1.0,0.667,b
0.223,0.336,1.0,b
for d,s in data
is just a nice way to unpack the dictionary (first item) and the value (second item). And the csv
module converts floats & integers to string, no need to bother for that.
you can do this as follows:
import csv
data = [({1: 0.1723, 2: 0.890, 3: 1.0}, 'a'), ({1: 0.0, 2: 1.0, 3: 0.667}, 'b'), ({1: 0.223, 2: 0.336, 3: 1.0}, 'b')]
rows = []
for the_dict, the_char in data:
row = []
# get values from dictionary and add it to row
for x in the_dict.values():
row.append(x)
# add char
row.append(the_char)
# ad row to rows list
rows.append(row)
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(rows)
Here is another solution:
import csv
data = [({1: 0.1723, 2: 0.890, 3: 1.0}, 'a'),
({1: 0.0, 2: 1.0, 3: 0.667}, 'b'),
({1: 0.223, 2: 0.336, 3: 1.0}, 'b')]
def make_row(elements):
row = list()
for obj in elements:
if isinstance(obj, dict):
row += obj.values()
else:
row.append(obj)
return row
with open('output.csv', 'w') as handle:
writer = csv.writer(handle)
for row in data:
writer.writerow(make_row(row))
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.