python – 将嵌套字典写入csv
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 将嵌套字典写入csv,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3392字,纯文字阅读大概需要5分钟。
内容图文
![python – 将嵌套字典写入csv](/upload/InfoBanner/zyjiaocheng/811/41c91920bbcb4adfbc9b7bfee9042dcb.jpg)
我有一本字典:
dic = {"Location1":{"a":1,"b":2,"c":3},"Location2":{"a":4,"b":5,"c":6}}
我想将这个字典列表为csv,最上面的键是最左边的列,子键是最上面一行的标题,每个后续行都填充了子键值,如下所示:
Location a b c
Location1 1 2 3
Location2 4 5 6
我使用以下脚本成功完成了哪些操作:
import csv
dic = {"Location1":{"a":1,"b":2,"c":3},"Location2":{"a":4,"b":5,"c":6}}
fields = ["Location","a","b","c"]
with open(r"C:\Users\tyler.cowan\Desktop\tabulated.csv", "w", newline='') as f:
w = csv.DictWriter(f, extrasaction='ignore', fieldnames = fields)
w.writeheader()
for k in dic:
w.writerow({field: dic[k].get(field) or k for field in fields})
特别之处在于我将这个测试用例写入一个真实的案例中,并最终将相当于我的位置键分配到其他列中.现在我的第一个想法很好,我必须搞砸了构建字典,但经过检查,我得到完全相同的字典格式,但更多的键值除外.然而输出就像
Location a b c d e f g h
Location1 1 2 3 Location1 7 8 9 10
Location2 4 5 6 Location2 2 3 4 5
以下是我的完整脚本
# -*- coding: utf-8 -*-
import os
import csv
def pretty(d, indent=0):
#prettify dict for visual Inspection
for key, value in d.items():
print('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
if value == "":
print("fubar")
print('\t' * (indent+1) + str(value))
inFolder = "Folder"
dirList = os.listdir(inFolder)
#print(dirList)
fields = [ 'Lat-Long']
allData = {}
for file in dirList:
fname, ext = os.path.splitext(file)
if fname not in fields:
fields.append(fname)
#handle .dat in this block
if ext.lower() == ".dat":
#print("found dat ext: " + str(ext))
with open(os.path.join(inFolder,file), "r") as f:
for row in f:
try:
row1 = row.split(" ")
if str(row1[0])+"-"+str(row1[1]) not in allData:
allData[str(row1[0])+"-"+str(row1[1])] = {}
else:
allData[str(row1[0])+"-"+str(row1[1])][fname] = row1[2]
except IndexError:
row2 = row.split("\t")
if str(row2[0])+"-"+str(row2[1]) not in allData:
allData[str(row2[0])+"-"+str(row2[1])] = {}
else:
allData[str(row2[0])+"-"+str(row2[1])][fname] = "NA"
elif ext.lower() == ".csv":
with open(os.path.join(inFolder,file), "r") as f:
for row in f:
row1 = row.split(",")
if str(row1[0])+"-"+str(row1[1]) not in allData:
allData[str(row1[0])+"-"+str(row1[1])] = {}
else:
allData[str(row1[0])+"-"+str(row1[1])][fname] = row1[2]
pretty(allData)
with open("testBS.csv", "w", newline='') as f:
w = csv.DictWriter(f, extrasaction='ignore', fieldnames = fields)
w.writeheader()
for k in allData:
w.writerow({field: allData[k].get(field) or k for field in fields})
输入数据如下:
"example.dat"
32.1 101.3 65
32.1 101.3 66
32.1 101.3 67
32.1 101.3 68
32.1 101.3 69
32.1 101.3 70
32.1 101.3 71
我想弄清楚如何诊断和解决行为,因为我似乎无法弄清楚测试和真实案例之间的区别.
解决方法:
可能的方法是创建一个csv头文件,其中包含所有子元素键的完整列表以及位置值.这样,所有subdictionary值都可以在其正确的“key”列下写入:
import csv
dic = {"Location1":{"a":1,"b":2,"c":3},"Location2":{"a":4,"b":5,"c":6}, "Location3":{'e':7,'f':8, 'g':9, 'h':10}, "Location4":{'e': 2, 'f': 3, 'g': 4, 'h': 5}}
header = sorted(set(i for b in map(dict.keys, dic.values()) for i in b))
with open('filename.csv', 'w', newline="") as f:
write = csv.writer(f)
write.writerow(['location', *header])
for a, b in dic.items():
write.writerow([a]+[b.get(i, '') for i in header])
输出:
location,a,b,c,e,f,g,h
Location1,1,2,3,,,,
Location2,4,5,6,,,,
Location3,,,,7,8,9,10
Location4,,,,2,3,4,5
内容总结
以上是互联网集市为您收集整理的python – 将嵌套字典写入csv全部内容,希望文章能够帮你解决python – 将嵌套字典写入csv所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。