簡體   English   中英

將嵌套字典寫入CSV,將長格式轉換為寬格式

[英]Write Nested Dictionary to CSV, Convert Long to Wide Format

嘗試將嵌套字典(請參見下面的示例)放入寬數據格式的CSV文件中。

讓我們把詞典稱為“船只” ,頂級鑰匙在哪里是船ID鑰匙。

"123abc": {
    "length": 50,
    "color": "Orange",
    "Weight": 75
},
"456xyz": {
    "length": 35,
    "color": "Green",
    "Weight": 55
}

現行守則

    with open('insertIntoFile.csv', 'w') as fileCSV:
         csvWriter = csv.writer(fileCSV, delimiter=',')
         for all_keys in boats:
              for sub_key in boats[ID]:
                   csvWriter.writerow([ID, sub_key, boats[ID][sub_key]])

輸出是

ID
123abc, length, 50
123abc, color, "Orange"
123abc, weight, 75
456xyz, length, 35
456xyz, color, "Green"
456xyz, weight, 55

我想找到一種方法在CSV寫入過程中添加另一個循環來獲得以下內容,這是我的理想輸出。

心願

ID, length, color, weight
123abc, 75, "Orange", 50
456xyz, 35, "Green", 35

謝謝。

您可以使用Pandas顯着簡化任務。 從字典創建數據框並將其保存到文件中:

import pandas as pd
df = pd.DataFrame(boats['ID']).T
df.index.name = 'ID' # The default name is "index"
df.reset_index().to_csv('insertIntoFile.csv', index=False)

您可以先寫入標題,然后將帶有字典值的連接ID鍵寫入文件:

from csv import writer

d = {
    "123abc": {"length": 50, "color": "Orange", "Weight": 75},
    "456xyz": {"length": 35, "color": "Green", "Weight": 55},
}

headers = ["ID", "length", "color", "weight"]

with open("insertIntoFile.csv", mode="w", newline="") as csvfile:
    writer = writer(csvfile)
    writer.writerow(headers)

    for row, data in d.items():
        writer.writerow([row] + list(data.values()))

你也可以使用csv.DictWriter

from csv import DictWriter

d = {
    "123abc": {"length": 50, "color": "Orange", "Weight": 75},
    "456xyz": {"length": 35, "color": "Green", "Weight": 55},
}

fieldnames = ["ID", "length", "color", "weight"]

with open("insertIntoFile.csv", mode="w", newline="") as csvfile:
    writer = DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

    for row, data in d.items():
        writer.writerow(
            {
                "ID": row,
                "length": data["length"],
                "color": data["color"],
                "weight": data["Weight"],
            }
        )

insertIntoFile.csv:

ID,length,color,weight
123abc,50,Orange,75
456xyz,35,Green,55

暫無
暫無

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

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