[英]How to open CSV with multiple values in each row and store it in a nested dictionary?
I'm new to python and trying to do the following: 我是python的新手,正在尝试执行以下操作:
Open a CSV file with 5 different values separated by comma. 用5个不同的值(以逗号分隔)打开一个CSV文件。
I want to store the data in a dictionary which key will be row[0]
. 我想将数据存储在字典中,该字典的键将是
row[0]
。
Suppose there are 4 rows so 4 primary keys, for each key I need to create another nested dictionary with 4 new keys, each key with the values of rows 1, 2, 3 and 4. 假设有4行,所以有4个主键,对于每个键,我需要使用4个新键创建另一个嵌套字典,每个键的行数分别为1、2、3和4。
Let's say the CSV contains: 假设CSV包含:
1,hi,1,2,3
2,yes,2,3,4
3,no,3,4,5
4,why,4,5,6
and I need to store: 我需要存储:
dict={'1': { 'key2':hi,'key3':1,'key4':2,'key5':3}, '2':{ }, '3':{}, '4':{} }
This is the code I'm using 这是我正在使用的代码
import csv
dict={}
reader = csv.reader(open('filename.csv', 'r'))
for row in reader:
key=row[0]
for key in dict:
dict[key]={}
dict[key][key2]=row[1]
dict[key][key3]=row[2]
dict[key][key4]=row[3]
dict[key][key5]=row[4]
What am I missing? 我想念什么?
The reason your code doesn't work is because for each row
you are iterating over keys of an empty dictionary for key in dict
resulting in no actions being taken. 您的代码不起作用的原因是,对于每一
row
您都在空字典for key in dict
进行迭代for key in dict
从而导致未采取任何操作。
Instead, if you would like to insert {'key2': row[1], 'key3': row[2], 'key4': row[3], 'key5': row[4]}
to dict[row[0]]
try the following. 相反,如果您想在
dict[row[0]]
上插入{'key2': row[1], 'key3': row[2], 'key4': row[3], 'key5': row[4]}
dict[row[0]]
尝试以下方法。 Also, avoid using variables named after builtin types, ie list
, set
, all
, dict
. 另外,避免使用以内置类型命名的变量,即
list
, set
, all
, dict
。
import csv
output_dict = {}
with open('filename.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
output_dict[row[0]] = {'key%d' % (i + 1): row[i] for i in xrange(1, 5)}
Here is code that does what you are asking: 以下是符合您要求的代码:
import csv
my_dictionary = {}
reader = csv.reader(open('filename.csv', 'r'))
for row in reader:
my_dictionary[row[0]] = {}
for index in range(1, len(row)):
my_dictionary[row[0]]['key' + str(index)] = row[index]
You should avoid naming a dictionary 'dict' because that is the name of the function that creates dictionary objects. 您应该避免命名字典“ dict”,因为那是创建字典对象的函数的名称。 Also, the variable 'key' gets overwritten by your iterator variable.
同样,变量“键”将被迭代器变量覆盖。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.