我试图从一个csv文件创建一个字典。csv文件的第一列包含唯一的键,第二列包含值。csv文件的每一行都表示字典中的唯一键、值对。我尝试使用csv文件。DictReader和csv。类的DictWriter,但我只知道如何为每一行生成一个新字典。我想要一本字典。这是我试图使用的代码:

import csv

with open('coors.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('coors_new.csv', mode='w') as outfile:
    writer = csv.writer(outfile)
    for rows in reader:
        k = rows[0]
        v = rows[1]
        mydict = {k:v for k, v in rows}
    print(mydict)

当我运行上面的代码时,我得到一个ValueError:太多的值来解包(预期2)。我如何从csv文件创建一个字典?谢谢。


当前回答

如果你有:

csv中只有一个键和一个作为键的值 不想导入其他包 想要一次创造字典

这样做:

mydict = {y[0]: y[1] for y in [x.split(",") for x in open('file.csv').read().split('\n') if x]}

它能做什么?

它使用列表推导式来分割行,最后一个“if x”用于忽略空行(通常在末尾),然后使用字典推导式将空行解压缩到字典中。

其他回答

也可以使用numpy。

from numpy import loadtxt
key_value = loadtxt("filename.csv", delimiter=",")
mydict = { k:v for k,v in key_value }

你可以用这个,它很酷:

import dataconverters.commas as commas
filename = 'test.csv'
with open(filename) as f:
      records, metadata = commas.parse(f)
      for row in records:
            print 'this is row in dictionary:'+rowenter code here

下面是一个CSV to Dict的方法:

import pandas

data = pandas.read_csv('coors.csv')

the_dictionary_name = {row.k: row.v for (index, row) in data.iterrows()}

以熊猫为例,这就容易得多。 假设你有以下CSV格式的数据,我们把它命名为test.txt / test.csv(你知道CSV是一种文本文件)

a,b,c,d
1,2,3,4
5,6,7,8

现在用熊猫

import pandas as pd
df = pd.read_csv("./text.txt")
df_to_doct = df.to_dict()

对于每一行,它都是

df.to_dict(orient='records')

就是这样。

许多解决方案已经发布,我想贡献我的解决方案,它适用于CSV文件中不同数量的列。 它创建一个每列有一个键的字典,每个键的值是一个包含该列元素的列表。

    input_file = csv.DictReader(open(path_to_csv_file))
    csv_dict = {elem: [] for elem in input_file.fieldnames}
    for row in input_file:
        for key in csv_dict.keys():
            csv_dict[key].append(row[key])