如何使用列表的内部字典返回特定的数据结构 [英] How to return a specific data structure with inner dictionary of lists
本文介绍了如何使用列表的内部字典返回特定的数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个csv文件(带有图像),并获取CSV文件,并创建一个格式为"{method},{number},{orbital_period},{mass},{distance},{year}
"的列表字典.
I have a csv file (image attached) and to take the CSV file and create a dictionary of lists with the format "{method},{number},{orbital_period},{mass},{distance},{year}
" .
到目前为止,我有代码:
So far I have code :
import csv
with open('exoplanets.csv') as inputfile :
reader = csv.reader(inputfile)
inputm = list(reader)
print(inputm)
但是我的输出像['Radial Velocity', '1', '269.3', '7.1', '77.4', '2006']
当我希望它看起来像:
"Radial Velocity" : {"number":[1,1,1], "orbital_period":[269.3, 874.774, 763.0], "mass":[7.1, 2.21, 2.6], "distance":[77.4, 56.95, 19.84], "year":[2006.0, 2008.0, 2011.0] } , "Transit" : {"number":[1,1,1], "orbital_period":[1.5089557, 1.7429935, 4.2568], "mass":[], "distance":[200.0, 680.0], "year":[2008.0, 2008.0, 2008.0] }
关于如何更改代码的任何想法?
Any ideas on how I can alter my code?
推荐答案
如果您不想使用熊猫,也许您正在寻找这样的东西:
If you don't want to use Pandas, maybe something like this is what you're looking for:
import csv
with open('exoplanets.csv') as inputfile :
reader = csv.reader(inputfile)
inputm = list(reader)
header = inputm.pop(0)
del header[0] # probably you don't want "#method"
# create and populate the final dictionary
data = {}
for row in inputm:
if row[0] not in data:
data[row[0]] = {h:[] for h in header}
for i, h in enumerate(header):
data[row[0]][h].append(row[i+1])
print(data)
这篇关于如何使用列表的内部字典返回特定的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文