简体   繁体   English

Python - 根据代表列和行(坐标)的 position 的键将字典中的值写入.csv

[英]Python - Write Values from Dictionary into .csv according to keys representing the position of column and row (coordinates)

I am having a dictionary where the keys represents a coordinate (column,row) of a specific value:我有一个字典,其中的键表示特定值的坐标(列、行):

d={(1,1) : value_1 , (1,2) : value_2 , (2,1) : value_3 , (2,2) : value_4}

The csv-file should only contain the values, but at the right position defined by the keys (column,row): csv 文件应该只包含值,但在右边 position 由键(列,行)定义:

value_1 , value_3
value_2 , value_4

I hope anybody can give me a hint, how i could handle this one?我希望有人能给我一个提示,我该如何处理这个?

If you are okay using Pandas, you could use the key coordinates to directly add the dictionary values to their appropriate location, like so:如果您可以使用 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)

Which would output the following data table as out.csv :哪个将 output 以下数据表作为out.csv

1.0,3.0
2.0,4.0

Take a look at Python's built in csv module:看看 Python 内置的 csv 模块:

https://docs.python.org/3/library/csv.html https://docs.python.org/3/library/csv.html

All you need to do is:您需要做的就是:

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")

The outputs are:输出是:

output1.csv : output1.csv

value_1,value_3
value_2,value_4

output2.csv : output2.csv

,value_3
value_2,value_4

output3.csv : output3.csv

,value_3
value_2,value_4
value_1,

Another very simple approach that will solve your problem:另一种非常简单的方法可以解决您的问题:

Say you have testread.csv with the following:假设您有 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

what you may do is:你可以做的是:

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()

You will get the following contents for testwrite.csv:您将获得 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将python字典写入CSV列:第一列的键,第二列的值 - Write python dictionary to CSV columns: keys to first column, values to second Python 3如何使用表示重叠坐标的元组键压缩字典 - python 3 how to compress a dictionary with tuple keys representing overlapping coordinates 将 Python 字典写入 CSV,其中键 = 列,值 = 行 - Write Python dictionary to CSV where where keys= columns, values = rows 如何在Python中编写具有多个键的字典,每个键具有多个值到csv? - How to write a dictionary with multiple keys, each with multiple values to a csv in Python? python将带有行和列标题的csv文件读入带有两个键的字典中 - python read csv file with row and column headers into dictionary with two keys 当行内容是相关键的键值(每列的标题)时,如何用python在csv中编写嵌套字典? - How to write nested dictionary in csv with python when the row contents are key values of related key (the header of each column)? 从字典中写入一个 CSV 并将值作为标题键对齐 - Write a CSV from Dictionary with Values as Header Keys Aligned Under 将字典(键和值)写入csv文件 - Write dictionary (keys and values) to a csv file 从字典创建 Python DataFrame,其中键是列名,值是行 - Create Python DataFrame from dictionary where keys are the column names and values form the row 将字典值写入csv python - Write dictionary values to csv python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM