csv file to list within dictionary

瘦欲@ 提交于 2020-06-16 03:34:52

问题


with open('exoplanets.csv') as infile:
    planets = {} 
    lines = infile.readline()
    for line in infile:
        reader = csv.reader(infile)
        number =  [line]

        methods, number, orbital_period, mass, distance, year = (s.strip(' ') for s in line.split(','))
        planets[methods] = (number, orbital_period, mass, distance, year)
        print(planets)

my code currently looks like that with the sample input:

and my output looks like this:

however, I want it to look like this:

{
  "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] }
}

can someone help me


回答1:


Check this code:

# import nan
from math import nan

# define source file
filename = 'EXOPLANETS.CSV - Sheet1.csv'

# read source file
with open(filename, 'r') as file:
    data = file.readlines()

# prepare output dictionary
output = {}

# read line by line
for idx, line in enumerate(data, 0):

    # split columns
    items = line.replace('\n', '').split(',')

    # extract inner dictionary's keys in a list: 'number', orbital_period', 'mass', 'distance', 'year'
    if idx == 0:
        values = [key for key in items[1:]]

    else:

        # add main key to the output dictionary: 'Radial Velocity', 'Imaging', 'Transit'
        if items[0] not in output.keys():
            output[items[0]] = {key : [] for key in values}

        # add value to the inner dictionary
        for jdx, key in enumerate(values, 1):

            # if the value is a valid number, convert it in float
            if items[jdx] != '':
                output[items[0]][key].append(float(items[jdx]))

            # if the value is not a valid number (empty cell), add a 'nan'
            else:
                output[items[0]][key].append(nan)

for items in output.items():
    print(items)

It will perform your task without using neither pandas or csv:

("Radial Velocity" : {"number":[1.0, 1.0, ...], "orbital_period":[269.3, 874.774, ...], "mass":[7.1, 2.21, ...], "distance":[77.4, 56.95, ...], "year":[2006.0, 2008.0, ...] ),

("Imaging" : {"number":[1.0, 1.0, ...], "orbital_period":[nan, nan, ...], "mass":[nan, nan, ...], "distance":[45.52, 165.0, ...], "year":[2005.0, 2007.0, ...] ),

("Transit" : {"number":[1.0, 1.0, ...], "orbital_period":[1.5089557, 1.7429935, ...], "mass":[nan, nan, ...], "distance":[nan, 200.0, ...], "year":[2008.0, 2008.0, ...] })

If the value in the source data is an empty cell, the code above will add a nan to the output. If this is an unwanted behavior and you want to jump the empy cells, use this code below:

# define source file
filename = 'EXOPLANETS.CSV - Sheet1.csv'

# read source file
with open(filename, 'r') as file:
    data = file.readlines()

# prepare output dictionary
output = {}

# read line by line
for idx, line in enumerate(data, 0):

    # split columns
    items = line.replace('\n', '').split(',')

    # extract inner dictionary's keys in a list: 'number', orbital_period', 'mass', 'distance', 'year'
    if idx == 0:
        values = [key for key in items[1:]]

    else:

        # add main key to the output dictionary: 'Radial Velocity', 'Imaging', 'Transit'
        if items[0] not in output.keys():
            output[items[0]] = {key : [] for key in values}

        # add value to the inner dictionary
        for jdx, key in enumerate(values, 1):

            # if the value is a valid number, convert it in float
            if items[jdx] != '':
                output[items[0]][key].append(float(items[jdx]))

for items in output.items():
    print(items)


来源:https://stackoverflow.com/questions/62239961/csv-file-to-list-within-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!