python用两个键将带有行和列标题的csv文件读入字典

2024-04-30 05:52:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下格式的csv文件

,col1,col2,col3
row1,23,42,77
row2,25,39,87
row3,48,67,53
row4,14,48,66

我需要把这个读入一本有两个键的字典

dict1['row1']['col2'] = 42
dict1['row4']['col3'] = 66

如果我尝试将csv.DictReader与默认选项一起使用

with open(filePath, "rb" ) as theFile:
    reader = csv.DictReader(theFile, delimiter=',')
    for line in reader:
    print line

我得到以下输出

{'': 'row1', 'col2': '42', 'col3': '77', 'col1': '23'}
{'': 'row2', 'col2': '39', 'col3': '87', 'col1': '25'}
{'': 'row3', 'col2': '67', 'col3': '53', 'col1': '48'}
{'': 'row4', 'col2': '48', 'col3': '66', 'col1': '14'}

我不知道如何处理这个输出来创建我感兴趣的字典类型。

为了完整起见,如果您能够解决如何将字典以上述格式写回csv文件的问题,它也会有所帮助


Tags: 文件csv字典格式readercol2col3col1
3条回答

您可以使用pandas来实现这一点,即使这有点过分了。pro是几乎没有任何代码可以获得预期的结果。

# Reading the file
df = pd.read_csv('tmp.csv', index_col=0)

# Creating the dict
d = df.transpose().to_dict(orient='series')

print(d['row1']['col2'])
42

输入文件的格式不便于用csv模块解析。我将分别解析头,然后逐行解析rest,通过,分割,一路上剥离并生成字典。工作代码:

from pprint import pprint

d = {}
with open("myfile.csv") as f:
    headers = [header.strip() for header in next(f).split(",")[1:]]

    for line in f:
        values = [value.strip() for value in line.split(",")]
        d[values[0]] = dict(zip(headers, values[1:]))

pprint(d)

印刷品:

{'row1': {'col1': '23', 'col2': '42', 'col3': '77'},
 'row2': {'col1': '25', 'col2': '39', 'col3': '87'},
 'row3': {'col1': '48', 'col2': '67', 'col3': '53'},
 'row4': {'col1': '14', 'col2': '48', 'col3': '66'}}

使用CSV模块:

import csv
dict1 = {}

with open("test.csv", "rb") as infile:
    reader = csv.reader(infile)
    headers = next(reader)[1:]
    for row in reader:
        dict1[row[0]] = {key: int(value) for key, value in zip(headers, row[1:])}

相关问题 更多 >