简体   繁体   English

如何打开每行具有多个值的CSV并将其存储在嵌套字典中?

[英]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 . 另外,避免使用以内置类型命名的变量,即listsetalldict

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.

相关问题 当行内容是相关键的键值(每列的标题)时,如何用python在csv中编写嵌套字典? - How to write nested dictionary in csv with python when the row contents are key values of related key (the header of each column)? 如何在Python中编写具有多个键的字典,每个键具有多个值到csv? - How to write a dictionary with multiple keys, each with multiple values to a csv in Python? Python:当一个键有多个值时,如何将字典写入csv文件,每个键是一个新行,但每个值是一个新列? - Python: How to write dictionary to csv file when one key has multiple values, each key is a new row, but each value is a new column? Python - Read.csv 作为具有多个键的字典并将匹配的键值存储为嵌套的列表列表 - Python - Read .csv as dictionary with multiple keys & store matching key values as nested List of Lists 如何在字典中存储多个值? - How to store multiple values in a dictionary? 需要获取 csv 文件中的每一行并存储在字典中 - need to fetch each row in csv file and store in a dictionary 使用python在csv中每一行的末尾附加字典或值列表 - Append Dictionary or list of values at the end of each row in csv using python 如何在 csv 文件的每一行中写入字典的每一项? - how to write each items of dictionary in each row of csv file? 如何定义 function 以从嵌套字典中提取 python 中每一行的值 - How do I define a function to extract values from nested dictionary for each row in python 编写具有多个值的字典以将数据存储在CSV文件的列中 - Write a dictionary with multiple values to store data in columns in the CSV file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM