0

I have a file comprising five columns seperated by commas, i.e.,

g,1,2,3,4 
c,4,2,6,8
d,5,6,8,9

I wish to read this file to a dictionary such that column 1 is the key and columns 2-4 are the integer values, i.e.,

d = {"g":[1, 2, 3, 4], "c":[4, 2, 6, 8], ...etc}

I've been playing around with a code snippet i found on the internet, but it returns a ValueError: too many values to unpack (expected 2)

d = {}
with open("file.csv") as f:
    for line in f:
       (key, val) = line.split(",")
       d[key] = int(val)
Crimson
  • 135
  • 7

5 Answers5

2

Here is one approach with the builtin csv module

import csv

with open('a.csv', newline='') as csvfile:
    value = {}
    for row in csv.reader(csvfile):
        value[row[0]] = list(map(int,row[1:]))
    print(value)

output:

{'g': [1, 2, 3, 4], 'c': [4, 2, 6, 8], 'd': [5, 6, 8, 9]}
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
1

Try this

import pandas as pd
 
df = pd.read_csv("file.csv")
dct = df.to_dict()
S3DEV
  • 8,768
  • 3
  • 31
  • 42
dimay
  • 2,768
  • 1
  • 13
  • 22
1

Something like

data = {}
with open('data.txt') as f:
  lines = [l.strip() for l in f]
  for line in lines:
    fields = line.split(',')
    data[fields[0]] = [int(x) for x in fields[1:]]
print(data)

output

{'g': [1, 2, 3, 4], 'c': [4, 2, 6, 8], 'd': [5, 6, 8, 9]}
balderman
  • 22,927
  • 7
  • 34
  • 52
1

Something like this ?

d = {}
with open("file.csv") as f:
    for line in f:
        line = line.strip()
        l = line.split(",")
        d[l[0]] = [int(e) for e in l[1:]]

print(d)

Output

{'g': [1, 2, 3, 4], 'c': [4, 2, 6, 8], 'd': [5, 6, 8, 9]}
LeMorse
  • 132
  • 6
1

You are almost there. Try this. I think it is quite readable.

d = {}
with open("file.csv") as f:
    for line in f:
       data = line.split(",")
       key = data[0]
       val = [int(x) for x in data[1:]]
       d[key] = val
alec_djinn
  • 10,104
  • 8
  • 46
  • 71