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

Wan*_*ind 7 python csv dictionary

我有以下格式的csv文件,

,col1,col2,col3
row1,23,42,77
row2,25,39,87
row3,48,67,53
row4,14,48,66
Run Code Online (Sandbox Code Playgroud)

我需要把它读成两个键的字典,这样

dict1['row1']['col2'] = 42
dict1['row4']['col3'] = 66
Run Code Online (Sandbox Code Playgroud)

如果我尝试使用csv.DictReader和默认选项

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

我得到以下输出

{'': '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'}
Run Code Online (Sandbox Code Playgroud)

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

为了完整起见,如果你能解决如何将字典写回到具有上述格式的csv文件中,它也会有所帮助

Tim*_*ker 16

使用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:])}
Run Code Online (Sandbox Code Playgroud)


Rom*_*ain 6

你可以使用pandas,即使它有点矫枉过正.专家认为,几乎没有任何代码可以获得预期的结果.

# 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
Run Code Online (Sandbox Code Playgroud)