尝试将嵌套字典(请参见下面的示例)转换成具有广泛数据格式的CSV文件。
让我们叫字典“ boats” ,其中最上层的键是Boat 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
谢谢。
答案 0 :(得分:2)
您可以使用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)
答案 1 :(得分:1)
您可以先简单地写标题,然后将带有字典值的级联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