Python - 根据表示列和行位置(坐标)的键将字典中的值写入.csv
Python - Write Values from Dictionary into .csv according to keys representing the position of column and row (coordinates)
我有一个字典,其中的键表示特定值的坐标(列、行):
d={(1,1) : value_1 , (1,2) : value_2 , (2,1) : value_3 , (2,2) : value_4}
csv 文件应仅包含值,但位于由键(列、行)定义的正确位置:
value_1 , value_3
value_2 , value_4
我希望有人能给我一个提示,我该如何处理这个问题?
如果您可以使用 Pandas,您可以使用键坐标直接将字典值添加到适当的位置,如下所示:
import pandas as pd
d = {
(1,1): 1,
(1,2): 2,
(2,1): 3,
(2,2): 4
}
df = pd.DataFrame()
for k, v in d.items():
df.at[k[1], k[0]] = v
df.to_csv('out.csv', index=False, header=False)
这将输出以下数据 table 作为 out.csv
:
1.0,3.0
2.0,4.0
看看 Python 的内置 csv 模块:
https://docs.python.org/3/library/csv.html
您只需:
import csv
def output_csv(input_dict, output_filename):
# translate original data dict into a list of dictionaries representing each row
output_list = []
for coord, value in input_dict.items():
while coord[1] > len(output_list):
# insert rows if the required row is not there
output_list.append({})
output_list[coord[1]-1][coord[0]] = value
# obtain the column field names
csv_fields = []
for row in output_list:
# check each row to make sure we have all the columns
if len(csv_fields) < len(row):
csv_fields = list(row)
# sort the fields in order
csv_fields.sort()
# open the output file for writing
with open(output_filename, 'w', newline='') as csvfile:
# init the csv DictWriter
writer = csv.DictWriter(csvfile,csv_fields, extrasaction='ignore',dialect='excel')
# write each row
for row in output_list:
writer.writerow(row)
d={(1,1) : 'value_1' , (1,2) : 'value_2' , (2,1) : 'value_3' , (2,2) : 'value_4'}
d2={(1,2) : 'value_2' , (2,1) : 'value_3' , (2,2) : 'value_4'}
d3={(1,3) : 'value_1' , (1,2) : 'value_2' , (2,1) : 'value_3' , (2,2) : 'value_4'}
output_csv(d, "output1.csv")
output_csv(d2, "output2.csv")
output_csv(d3, "output3.csv")
输出是:
output1.csv
:
value_1,value_3
value_2,value_4
output2.csv
:
,value_3
value_2,value_4
output3.csv
:
,value_3
value_2,value_4
value_1,
另一种非常简单的方法可以解决您的问题:
假设您 testread.csv 具有以下内容:
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
你可以做的是:
import csv
d={(1,1) : "a" , (1,2) : "b" , (2,1) : "c" , (2,2) : "d"}
#open the file you need to modify and create a list of all rows
f = open('testread.csv', 'r')
reader = csv.reader(f)
rowlist = list(reader)
f.close()
for (k,v) in zip(d.keys(),d.values()):
rowlist[k[0]][k[1]]= v
#open the destination file and modify it
new_list = open('testwrite.csv', 'w', newline = '')
csv_writer = csv.writer(new_list)
csv_writer.writerows(rowlist)
new_list.close()
您将获得testwrite.csv的以下内容:
1,2,3,4,5
1,a,b,4,5
1,c,d,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
我有一个字典,其中的键表示特定值的坐标(列、行):
d={(1,1) : value_1 , (1,2) : value_2 , (2,1) : value_3 , (2,2) : value_4}
csv 文件应仅包含值,但位于由键(列、行)定义的正确位置:
value_1 , value_3
value_2 , value_4
我希望有人能给我一个提示,我该如何处理这个问题?
如果您可以使用 Pandas,您可以使用键坐标直接将字典值添加到适当的位置,如下所示:
import pandas as pd
d = {
(1,1): 1,
(1,2): 2,
(2,1): 3,
(2,2): 4
}
df = pd.DataFrame()
for k, v in d.items():
df.at[k[1], k[0]] = v
df.to_csv('out.csv', index=False, header=False)
这将输出以下数据 table 作为 out.csv
:
1.0,3.0
2.0,4.0
看看 Python 的内置 csv 模块:
https://docs.python.org/3/library/csv.html
您只需:
import csv
def output_csv(input_dict, output_filename):
# translate original data dict into a list of dictionaries representing each row
output_list = []
for coord, value in input_dict.items():
while coord[1] > len(output_list):
# insert rows if the required row is not there
output_list.append({})
output_list[coord[1]-1][coord[0]] = value
# obtain the column field names
csv_fields = []
for row in output_list:
# check each row to make sure we have all the columns
if len(csv_fields) < len(row):
csv_fields = list(row)
# sort the fields in order
csv_fields.sort()
# open the output file for writing
with open(output_filename, 'w', newline='') as csvfile:
# init the csv DictWriter
writer = csv.DictWriter(csvfile,csv_fields, extrasaction='ignore',dialect='excel')
# write each row
for row in output_list:
writer.writerow(row)
d={(1,1) : 'value_1' , (1,2) : 'value_2' , (2,1) : 'value_3' , (2,2) : 'value_4'}
d2={(1,2) : 'value_2' , (2,1) : 'value_3' , (2,2) : 'value_4'}
d3={(1,3) : 'value_1' , (1,2) : 'value_2' , (2,1) : 'value_3' , (2,2) : 'value_4'}
output_csv(d, "output1.csv")
output_csv(d2, "output2.csv")
output_csv(d3, "output3.csv")
输出是:
output1.csv
:
value_1,value_3
value_2,value_4
output2.csv
:
,value_3
value_2,value_4
output3.csv
:
,value_3
value_2,value_4
value_1,
另一种非常简单的方法可以解决您的问题:
假设您 testread.csv 具有以下内容:
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
你可以做的是:
import csv
d={(1,1) : "a" , (1,2) : "b" , (2,1) : "c" , (2,2) : "d"}
#open the file you need to modify and create a list of all rows
f = open('testread.csv', 'r')
reader = csv.reader(f)
rowlist = list(reader)
f.close()
for (k,v) in zip(d.keys(),d.values()):
rowlist[k[0]][k[1]]= v
#open the destination file and modify it
new_list = open('testwrite.csv', 'w', newline = '')
csv_writer = csv.writer(new_list)
csv_writer.writerows(rowlist)
new_list.close()
您将获得testwrite.csv的以下内容:
1,2,3,4,5
1,a,b,4,5
1,c,d,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5