目的:读取CSV文件中的内容,并将其转换为字典
代码:
import csv
import os
def csv2dict(strFilePath):
if not os.path.isfile(strFilePath):
print('file is not exist')
return None
l = []
with open(strFilePath) as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
d = dict([(headers[i], row[i]) for i in range(len(headers))])
l.append(d)
f.close()
return headers, l总结:
先导入csv模块/包,再打开文件,将文件作为参数传给reader()。然后就可以用next()逐行读取文件。
【知识点】
1、路径文件是否存在,可直接使用os包中isfile方法直接判断
2、next函数:
将可迭代对象(如列表、字典、元组、字符串等)进行读取,并在循环中不断返回下一个值,直到对象结束。
其中,如果用next(f_csv,'end'),最后打印时会返回“end”
3、dict函数,dict(key/value):
入参可以为空、字典、key和value、列表、zip函数等,如下。本次代码里使用的就是含多个元组的列表
其中,[(headers[i], row[i]) for i in range(len(headers))] 是生成多个元组的列表推导式写法,在二维数组章节中有提到过。
dict0 = dict()
print('dict0:', dict0)
dict1 = dict({'three': 3, 'four': 4})
print('dict1:', dict1)
dict2 = dict(five=5, six=6)
print('dict2:', dict2)
dict3 = dict([('seven', 7), ('eight', 8)])
print('dict3:', dict3)
dict5 = dict(zip(['eleven', 'twelve'], [11, 12]))
print('dict5:', dict5)结果:
('dict0:', {})
('dict1:', {'four': 4, 'three': 3})
('dict2:', {'six': 6, 'five': 5})
('dict3:', {'seven': 7, 'eight': 8})
('dict5:', {'eleven': 11, 'twelve': 12})
问题:字典传值如果是含多个列表或者元组的字典呢,结果会怎么样呢?
试验如下:
dict1 = dict([['seven', 7], ['eight', 8]])
print('dict1:', dict1)
dict2 = dict([('seven', 7), ('eight', 8)])
print('dict2:', dict2)
dict3 = dict({('seven', 7), ('eight', 8)})
print('dict3:', dict3)
dict4 = dict({['seven', 7], ['eight', 8]})
print('dict4:', dict4)
dict5 = dict({{'seven': 7}, {'eight': 8}})
print('dict5:', dict5)结果:
Traceback (most recent call last):
File 'E://TestPython/src/huawei/test.py', line 10, in <module>
dict4 = dict({['seven', 7], ['eight', 8]})
TypeError: unhashable type: 'list'
('dict1:', {'seven': 7, 'eight': 8})
('dict2:', {'seven': 7, 'eight': 8})
('dict3:', {'seven': 7, 'eight': 8})
从结果来看,dict4使用方法有误(其实dict5也是失败的),并且错误内容 为:TypeError: unhashable type: 'list',即字典内的参数为列表,非哈希类型
【引申知识点】:
1、什么是哈希类型:可变类型的数据不可哈希,如列表,字典;不可变的数据是哈类类型,如数值、字母、字符串、数字、元组
2、Python不支持dict的key为list或dict类型,因为list和dict类型是unhashable(不可哈希),因此这就是为什么dict4/dict5调用 失败,而dict3能成功的原因
3、为什么ditc1/dict2能成功呢? 因为列表是根据位置或者索引来定义的,并没有对类型的限制





































苏公安网备 32011402010933号