[英]python read csv file with row and column headers into dictionary with two keys
我有以下格式的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文件中,它也會有所幫助
使用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:])}
你可以使用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
使用csv
模塊解析輸入文件的格式並不方便。 我想單獨解析頭,然后解析一行其余線,通過拆分,
,剝離和沿途使字典。 工作代碼:
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'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.