文档开发者中心
我的

【python成长之路】csv文件转换成字典数据


目的:读取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能成功呢? 因为列表是根据位置或者索引来定义的,并没有对类型的限制


点赞
收藏
回复
分享
举报
浏览1433 发布于2019-07-17 02:54未知归属地
全部评论
最多点赞
最新发布
最早发布
暂无评论
暂无评论
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要发帖子

了解社区公约,与您携手共创和谐专业的开发者社区。