简体   繁体   English

将 csv 文件读入字典

[英]Reading a csv file into a dictionary

My code looks like this:我的代码如下所示:

from sys import argv
import csv

person = {}

file = argv[1]
sequence = (open(argv[2], 'r').read()).strip()

with open(file, 'r', newline = '') as csvfile:
    reader = csv.reader(csvfile)
    for k, v0, v1, v2, v3, v4, v5, v6, v7 in reader:
        person[k] = [v0, v1, v2, v3, v4, v5, v6, v7]

Is there any other way to iterate through the columns to add in the dictionary more succinctly or efficiently?有没有其他方法可以遍历列以更简洁或更有效地添加到字典中? As in, for example, if you wouldn't know the number of columns?例如,如果您不知道列数?

You can use list slicing to achieve this: use the first element in row as the key, and the remaining elements as the value.您可以使用列表切片来实现这一点:使用行中的第一个元素作为键,其余元素作为值。


with open(file, 'r', newline = '') as csvfile:
    for row in csv.reader(csvfile):
        person[row[0]] = row[1:]

You could use unpacking :您可以使用unpacking

with open(file, 'r', newline = '') as csvfile:
    reader = csv.reader(csvfile)
    for key, *values in reader:
        person[key] = values

You can also read the csv file directly into a pandas dataframe:您还可以将csv文件直接读入 Pandas 数据帧:

import pandas as pd

data = pd.read_csv("filename.csv")

then put it into a dictionary然后放入字典

data.to_dict()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM