Python CSV import with nested list creation

安稳与你 提交于 2020-01-04 04:19:07

问题


I am trying to simply import a .csv into Python. I've read numerous documents but for the life of me I can't figure out how to do the following.

The CSV format is as follows

NYC,22,55
BOSTON,39,22

I'm trying to generate the following : {NYC = [22,55], BOSTON = [39,22]} so that I can call i[0] and i[1] in a loop for each variable.

I've tried

import csv
input_file = csv.DictReader(open("C:\Python\Sandbox\longlat.csv"))

for row in input_file:
print(row)

Which prints my variables, but I dont know hot to nest two numeric values within the city name and generate the list that im hoping to get.

Thanks for your help, sorry for my rookie question -


回答1:


If you are not familiar with python comprehensions, you can use the following code that uses a for loop:

import csv

with open('C:\Python\Sandbox\longlat.csv', 'r') as f:
    reader = csv.reader(f)
    result = {}
    for row in reader:
        result[row[0]] = row[1:]

The previous code works if you want the numbers to be string, if you want them to be numbers use:

import csv

with open('C:\Python\Sandbox\longlat.csv', 'r') as f:
    reader = csv.reader(f)
    result = {}
    for row in reader:
        result[row[0]] = [int(e) for i in row[1:]] # float instead of int is also valid



回答2:


Use dictionary comprehension:

import csv

with open(r'C:\Python\Sandbox\longlat.csv', mode='r') as csvfile:
    csvread = csv.reader(csvfile)
    result = {k: [int(c) for c in cs] for k, *cs in csvread}

This works in python-3.x, and produces on my machine:

>>> result
{'NYC': [22, 55], 'BOSTON': [39, 22]}

It also works for an arbitrary number of columns.

In case you use python-2.7, you can use indexing and slicing over sequence unpacking:

import csv

with open(r'C:\Python\Sandbox\longlat.csv', mode='r') as csvfile:
    csvread = csv.reader(csvfile)
    result = {row[0]: [int(c) for c in row[1:]] for row in csvread}



回答3:


Each row will have 3 values. You want the first as the key and the rest as the value.

>>> row
['NYC','22','55']

>>> {row[0]: row[1:]}
{'NYC': ['22', '55']}

You can create the whole dict:

lookup = {row[0]: row[1:] for row in input_file}



回答4:


You can also use pandas like so:

import pandas as pd

df = pd.read_csv(r'C:\Python\Sandbox\longlat.csv')

result = {}
for index, row in df.iterrows():
    result[row[0]] = row[1:]



回答5:


Heres a hint. Try familiarizing yourself with the str.split(x) function

 strVar = "NYC,22,55"
 listVar = strVar.split(',') # ["NYC", "22", "55"]
 cityVar = listVar[0]        # "NYC"
 restVar = listVar[1:];      # ["22", "55"]

 # If you want to convert `restVar` into integers
 restVar = map(int, restVar)


来源:https://stackoverflow.com/questions/46652131/python-csv-import-with-nested-list-creation

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