可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value pair within the dictionary. I tried to use the csv.DictReader
and csv.DictWriter
classes, but I could only figure out how to generate a new dictionary for each row. I want one dictionary. Here is the code I am trying to use:
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)
When I run the above code I get a ValueError: too many values to unpack (expected 2)
. How do I create one dictionary from a csv file? Thanks.
回答1:
I believe the syntax you were looking for is as follows:
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)
mydict = {rows[0]:rows[1] for rows in reader}
Alternately, for python <= 2.7.1, you want:
mydict = dict((rows[0],rows[1]) for rows in reader)
回答2:
import csv
reader = csv.reader(open(\'filename.csv\', \'r\'))
d = {}
for row in reader:
k, v = row
d[k] = v
回答3:
Open the file by calling open and then csv.DictReader
.
input_file = csv.DictReader(open(\"coors.csv\"))
You may iterate over the rows of the csv file dict reader object by iterating over input_file.
for row in input_file:
print row
OR
To access first line only
dictobj = csv.DictReader(open(\'coors.csv\')).next()
回答4:
You have to just convert csv.reader to dict:
~ >> cat > 1.csv
key1, value1
key2, value2
key2, value22
key3, value3
~ >> cat > d.py
import csv
with open(\'1.csv\') as f:
d = dict(filter(None, csv.reader(f)))
print(d)
~ >> python d.py
{\'key3\': \' value3\', \'key2\': \' value22\', \'key1\': \' value1\'}
回答5:
You can also use numpy for this.
from numpy import loadtxt
key_value = loadtxt(\"filename.csv\", delimiter=\",\")
mydict = { k:v for k,v in key_value }
回答6:
This isn\'t elegant but a one line solution using pandas.
import pandas as pd
pd.read_csv(\'coors.csv\', header=None, index_col=0, squeeze=True).to_dict()
If you want to specify dtype for your index (it can\'t be specified in read_csv if you use the index_col argument because of a bug):
import pandas as pd
pd.read_csv(\'coors.csv\', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()
回答7:
I\'d suggest adding if rows
in case there is an empty line at the end of the file
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)
mydict = dict(row[:2] for row in reader if row)
回答8:
If you are OK with using the numpy package, then you can do something like the following:
import numpy as np
lines = np.genfromtxt(\"coors.csv\", delimiter=\",\", dtype=None)
my_dict = dict()
for i in range(len(lines)):
my_dict[lines[i][0]] = lines[i][1]
回答9:
You can use this, it is pretty cool:
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
回答10:
One-liner solution
import pandas as pd
dict = {row[0] : row[1] for _, row in pd.read_csv(\"file.csv\").iterrows()}