[英]How to write dict in certain format to file
假設我有多個 dict 列表,類似於
list_one = [{'genre': 'Action', 'amount': 141, 'meanScore': 82}, {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]
list_two = [{'genre': 'Horror', 'amount': 11, 'meanScore': 62}, {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]
我的目標是將其寫入表單中的文件
Action Comedy Horror
list_one meanScore meanScore
amount amount
list_two meanScore meanScore
amount amount
我不太熟悉 dict 以及存儲它們的最佳方法是什么,但似乎 csv- 文件很受歡迎。 我試圖在這里使用這個答案來解決我的問題,但我很難理解@MarkLongair 的作用以及如何將其擴展到我的問題。 我擔心的主要事情之一是並非每個流派都是每個列表的一部分,所以我不知道如何檢查現有的 csv 文件是否存在密鑰、它位於何處以及如何將值寫入右列。
由於我無法真正理解鏈接的答案,我嘗試了一些類似的方法
from pandas import DataFrame
list_one = [{'genre': 'Action', 'amount': 141, 'meanScore': 82},
{'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]
list_two = [{'genre': 'Horror', 'amount': 11, 'meanScore': 62},
{'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]
DataFrame(list_one).to_csv('test.csv')
DataFrame(list_two).to_csv('test.csv')
這並沒有真正起作用,因為數據被覆蓋了,我想成為列的東西被轉換為行......
我不知道如何繼續這里的形式或正確的方向是什么......有人可以幫忙嗎?
在不使用 Pandas 的情況下解決此問題的一種方法 [編輯:我看到您已經編輯提到這一點] 是創建一個函數來查看您的字典之一,並撰寫適當的 CSV 文本行。
def generate_row(separator, headers, data_type, data_list, list_name):
data_by_genre = {k: '' for k in headers}
for data in data_list:
data_by_genre[data['genre']] = str(data[data_type])
output_text = separator.join([data_by_genre[genre] for genre in headers]) + '\n'
# If it's 'amount', then the row starts with the name. Otherwise that space is blank.
if data_type == 'amount':
output_text = list_name + output_text
return output_text
list_one = [{'genre': 'Action', 'amount': 141, 'meanScore': 82}, {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]
list_two = [{'genre': 'Horror', 'amount': 11, 'meanScore': 62}, {'genre': 'Comedy', 'amount': 191, 'meanScore': 82}]
headers = ['', 'Action', 'Comedy', 'Horror']
separator = ','
f = open('new.csv', 'w')
f.write(separator.join(headers))
f.write('\n')
f.write(generate_row(separator, headers, 'amount', list_one, 'list_one'))
f.write(generate_row(separator, headers, 'meanScore', list_one, 'list_one'))
f.write(generate_row(separator, headers, 'amount', list_two, 'list_two'))
f.write(generate_row(separator, headers, 'meanScore', list_two, 'list_two'))
f.close()
如果您想使用制表符分隔而不是逗號,我將“分隔符”設為變量。
但是,如果您想使用 Pandas,您可以編寫一些內容來重新格式化您的數據,使其看起來像這樣,因此它可以“正確”地寫入。
data1 = [{'Action': 141, 'Comedy': 191, 'Horror': None},
{'Action': 82, 'Comedy': 82, 'Horror': None},
{'Action': None, 'Comedy': 191, 'Horror': 11},
{'Action': None, 'Comedy': 82, 'Horror': 62}]
DataFrame(data1).to_csv('test.csv')
在您的問題的第一個版本中,您沒有提到您在 Pandas 中操作,這與 Python 標准庫和重要信息確實不同。 Pandas 並不是真的需要這樣做,但我假設您出於其他原因使用 Pandas。
DataFrame(list1 + list2).to_csv('test.csv')
也可以看看
如果您想在寫入而不是在轉換為數據幀之前組合列表時追加。
pandas 之外的其他解決方案是 csv 庫中的 csv.DictWriter 或 JSON 序列化(如果不需要 CSV)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.