簡體   English   中英

Python 3-將字典和字典值寫入CSV文件

[英]Python 3- Writing dictionaries with dictionary values to CSV files

我已經嘗試過google-,但是找不到適合字典值的字典的解決方案。 讓我解釋一些簡單。

我有一個票證代碼字典,每個票證代碼是另一個詞典,包含“名稱”和“兌現”-名稱是票證所有者,而被兌現是票證是否已兌現。 數據是從名為TicketCodes的csv文件加載的,該文件包含1000行數據。 我有一個可以截斷文件以准備寫入的系統,但是我發現的寫入CSV的解決方案不起作用。 如果這是重復的郵件,我深表歉意。 如果是,請您將我鏈接到解決方案嗎? 非常感謝你!

JSON是寫出python dict數據的更好的格式。 但是,如果所有dict的鍵都相同,則可能會以dict的鍵作為列名來格式化CSV文檔。

例如:

# Assuming the data is a list of dictionaries
the_data = [{'col1': 'data1', 'col2': 'data2'},
            {'col1': 'data3', 'col2': 'data4'},
            {'col1': 'data5', 'col2': 'data6'},
            {'col1': 'data7', 'col2': 'data8'}]

# Build a list of the column names.
# This could be done with list(the_data[0].keys())
# But then you have no control over the column ordering
column_names = ['col1', 'col2']

# Print out column names
print(",".join(column_names))

# Print out data
for row in the_data:
    print(",".join([row[field] for field in column_names]))

輸出:

col1,col2
data1,data2
data3,data4
data5,data6
data7,data8

注意:在我的示例中,我剛剛打印了CSV數據,但是將這些數據寫入文件將是微不足道的。

另外,要將the_data寫入JSON格式,就像執行以下操作一樣簡單:

>>> import json
>>> json.dumps(the_data)

'[{"col2": "data2", "col1": "data1"}, {"col2": "data4", "col1": "data3"}, {"col2": "data6", "col1": "data5"}, {"col2": "data8", "col1": "data7"}]'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM