简体   繁体   English

将嵌套字典写入CSV,将长格式转换为宽格式

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

Trying to get a nested dictionary (see example below) into a CSV file in a wide data format. 尝试将嵌套字典(请参见下面的示例)放入宽数据格式的CSV文件中。

Let's call the dictionary "boats" , where to top-level key is the boat ID key. 让我们把词典称为“船只” ,顶级钥匙在哪里是船ID钥匙。

Example

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

Current Code 现行守则

    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]])

The output is 输出是

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

I'm trying to figure out a way to add another loop in the CSV writing process to get the following, which is my ideal output. 我想找到一种方法在CSV写入过程中添加另一个循环来获得以下内容,这是我的理想输出。

Aspiration 心愿

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

Thanks. 谢谢。

You can significantly simplify the task with Pandas. 您可以使用Pandas显着简化任务。 Create a dataframe from the dictionary and save it to the file: 从字典创建数据框并将其保存到文件中:

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)

You can simply write the headers first, then write the concatenated ID key with the dictionary values to the file: 您可以先写入标题,然后将带有字典值的连接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()))

You can also use csv.DictWriter : 你也可以使用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: 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