简体   繁体   English

在写入csv时使用字典键作为坐标

[英]Using dictionary keys as coordinates when writing to csv

I have a dictionary which has cell coordinates as the keys and the desired cell content as the value, eg: 我有一个字典,其中单元格坐标为键,所需的单元格内容为值,例如:

dict1 = {'AN32': '2', 'AZ17': '47', ect...}

The cell range is D4: AZ52 细胞范围是D4: AZ52

I want to write this into a csv file. 我想把它写成一个csv文件。

The problem I am encountering when it comes to design is that the dictionary isn't necessarily ordered alphabetically or numberically as can be seen in the example above. 我在设计时遇到的问题是字典不一定按字母或数字排序,如上例所示。

I know how to write to a .csv file with 我知道如何写入.csv文件

with open('example.csv', 'w') as f:

    for i in dict1:

        f.write(str(dict1[i]) + ',')

this would write the values out in order, which would mean they wouldn't be in the correct cell, I need them to be in the cell which is specified by their key. 这将按顺序写出值,这意味着它们不在正确的单元格中,我需要它们位于由其键指定的单元格中。

This code uses a list comprehension to build each row. 此代码使用列表推导来构建每一行。

First we create a list of the column labels, using the uppercase string from the string module, and we build a list of all the column labels using a simple list comprehension. 首先,我们使用string模块中的uppercase字符串创建列标签列表,然后使用简单的列表解析构建所有列标签的列表。

Then we use a slightly more complicated list comprehension that makes a key by combining each column label with the current row number (converted to a string). 然后我们使用稍微复杂的列表推导,通过将每个列标签与当前行号(转换为字符串)组合来创建键。 That key is passed to dict1 's .get() method to get the value associated with that key. 该键被传递给dict1.get()方法以获取与该键相关联的值。 We use an empty string '' as the 2nd arg to .get() so that if a key doesn't exist in the dict we get an empty string. 我们使用空字符串''作为.get()的第二个arg,这样如果dict中不存在键,我们得到一个空字符串。

Then we use the .join() method to join all those strings, separated by commas. 然后我们使用.join()方法连接所有这些字符串,用逗号分隔。

from string import uppercase

#Make a list of the column letters
cols = list(uppercase[3:]) + ['A' + c for c in uppercase]
#print(cols)

with open('example.csv', 'w') as f:
    for r in range(4, 53):
        row = ','.join([dict1.get(c + str(r), '') for c in cols])
        f.write(row + '\n')

If the values in dict1 are actually int rather than strings, then you need to convert them to strings before attempting to join them. 如果dict1中的值实际上是int而不是字符串,那么在尝试连接它们之前需要将它们转换为字符串。 Change the list comprehension to 将列表理解更改为

row = ','.join([str(dict1.get(c + str(r), '')) for c in cols])

That will cope even if some values are strings and some are numbers. 即使某些值是字符串而某些值是数字,这也可以应对。

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

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