Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将csv文件转换为字典_Python 3.x - Fatal编程技术网

Python 3.x 将csv文件转换为字典

Python 3.x 将csv文件转换为字典,python-3.x,Python 3.x,我正在尝试使用以下结构将csv转换为字典: { "0": {"val1": 1, "val2": 2, "val3": 3, ..., "valn": n}, "1": {"val1": 45, "val2": 7, "val3": None, ..., "valn": 68}, } 其中as val1、val2等是列的标题名,“0”和“1”是行数 我试过: dicti = { i : reader[i] for i in range(0, len(reader) ) } 但我得到了以下结果

我正在尝试使用以下结构将csv转换为字典:

{
"0": {"val1": 1, "val2": 2, "val3": 3, ..., "valn": n},
"1": {"val1": 45, "val2": 7, "val3": None, ..., "valn": 68},
}
其中as val1、val2等是列的标题名,“0”和“1”是行数

我试过:

dicti = { i : reader[i] for i in range(0, len(reader) ) }
但我得到了以下结果:

{
 1: ['value1','value2'],
 2: ['value_x', 'value_y']
  ...
}

但是我没有达到我想要的结果

我感谢任何进一步的澄清。 多谢各位

CSV内容如下:

color,property,type,id
red,house,building,02 

{
"0": {"color": "red", "property": "house", "type": "building", ..., "valn": n},
"1": {"color": "blue", "property": "farm", "type": "area", ..., "valn": n},
}

这对您有用吗?

获取标题的最简单方法是使用。另外,使用
enumerate
获取更具Python风格的代码,以获取行的索引

import csv

with open('file') as f:
    reader = csv.DictReader(f)
    d = {row_index : row for row_index , row in enumerate(reader)}
用这个CSV

h1,h2,h3
a,b,c
d,e,f
您可以通过
d
获得以下信息:

{0: OrderedDict([('h1', 'a'), ('h2', 'b'), ('h3', 'c')]),
 1: OrderedDict([('h1', 'd'), ('h2', 'e'), ('h3', 'f')])}

如果您坚持使用“常规”字典作为值(我看不出任何原因),您可以使用
d={row\u index:dict(row)作为row\u索引,row in enumerate(reader)}

谢谢您,但是使用此解决方案,我没有得到我想要的格式,这应该与我的第一个代码片段类似question@js352你为什么在乎?它只是
OrderedDict
的字符串表示形式。您仍然可以非常轻松地将其作为“普通”词典访问,即
d[0]['h1']
。如果您指的是一个事实,即在您的示例中,行索引是字符串,只需执行
str(row_index)
,但我看不出这样做有任何好处。索引在很大程度上是整数definition@js352无论哪种方式,如果您坚持,您都可以使用
d={row\u index:dict(row)作为row\u索引,row in enumerate(reader)}
代替。谢谢您的回答。现在,我正试图找出如何在不使用csv.DictReader()或类似工具的情况下实现这一点。我的意思是,自己创建字典,从头开始排序键和值。使用
d={row\u index:row for row\u index,row in enumerate(line)}
可以获得一个字典,其中包含问题中所述的所有值,但没有键。这样做的最佳方式是什么?这甚至不接近OP想要的输出,而且只有当每行正好有2个元素时(并且仍然提供错误的输出),它才起作用
h1,h2,h3
a,b,c
d,e,f
{0: OrderedDict([('h1', 'a'), ('h2', 'b'), ('h3', 'c')]),
 1: OrderedDict([('h1', 'd'), ('h2', 'e'), ('h3', 'f')])}