繁体   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