AlejandroEVN
AlejandroEVN

Reputation: 3

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?

Upvotes: 0

Views: 89

Answers (3)

snakecharmerb
snakecharmerb

Reputation: 55630

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:]

Upvotes: 2

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

You could use unpacking:

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

Upvotes: 1

David Collins
David Collins

Reputation: 900

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()

Upvotes: 0

Related Questions