简体   繁体   中英

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 :

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:

import pandas as pd

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

then put it into a dictionary

data.to_dict()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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