我想將 CSV 檔案轉換為字典串列。例如,我有一個 CSV 檔案,其中包含以下順序的資料:
姓名、愛好、年齡
薩米,足球,6
安吉拉,國際象棋,12
輸出應如下所示:
[
{"name": "Sammy", "hobby": "football", "age": "6"},
{"name": "Angela", "hobby": "chess", "age": "12"}
]
你有什么建議嗎?
uj5u.com熱心網友回復:
如果您可以使用Pandas,則可以這樣做 -
import pandas as pd
df = pd.read_csv('/path/to/csv/file')
records = df.to_dict(orient='records')
輸出應該是這樣的 -
[
{"name": "Sammy", "hobby": "football", "age": "6"},
{"name": "Angela", "hobby": "chess", "age": "12"}
]
在這里,我們正在閱讀的CSV檔案作為大熊貓據幀,然后轉換dataframe到dict。如果pandas不可用,請使用安裝
pip install pandas
uj5u.com熱心網友回復:
您只能將此代碼與 csv 模塊一起使用:
import csv
with open(filename, mode='r') as infile:
reader = csv.reader(infile, skipinitialspace=True)
keys = next(reader)
ret_list = []
for row in reader:
ret_list.append({})
for key, value in zip(keys, row):
ret_list[-1][key] = value
更新: 這是更實用的解決方案:
import csv
with open(filename, mode='r') as infile:
reader = csv.DictReader(infile, skipinitialspace=True)
d = [r for r in reader]
uj5u.com熱心網友回復:
這是一種創建字典串列的方法;
import pandas as pd
# Replace './a.xlsx' with path to your file
# In case file is in csv use pd.read_csv instead
df = pd.read_excel('./a.xlsx')
# Create an empty list to hold the list of dictionaries
list_of_dicts = list()
# Use iterrows to iterate over all rows
for index, row in df.iterrows():
# Empty dictionary to be used as tmp value for each dict in list
dict_person = {}
# Iterate over each column on the row, update the dictionary key and value
for col in range(len(row.index)):
dict_person.update({str(row.index[col]) : row[col]})
# Add the temporary dict to the list
list_of_dicts.append(dict_person)
會產生結果;
[{'name': 'Sammy', 'hobby': 'football', 'age': 6},
{'name': 'Angela', 'hobby': 'chess', 'age': 12}]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/326236.html
