简体   繁体   English

Python - 如何从 .csv 文件读取到字典?

[英]Python - How to read from .csv file to a dictonary?

I have a file comprising five columns seperated by commas, ie,我有一个由逗号分隔的五列组成的文件,即,

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, ie,我希望将此文件读入字典,以便第 1 列是键,第 2-4 列是整数值,即,

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)我一直在玩我在互联网上找到的代码片段,但它返回一个 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)

Here is one approach with the builtin csv module这是内置csv 模块的一种方法

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

Try this尝试这个

import pandas as pd
 
df = pd.read_csv("file.csv")
dct = df.to_dict()

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

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

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

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

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