python读取csv存为字典_从csv文件读取数据放入字典python

那不是一个csv文件,csv模块帮不了你。在csv文件中,每一行都有相等数量的列字段,这些字段由逗号等已知字符分隔。您需要为这些数据编写自己的解析器。在

这个脚本将建立字典(除了它使用一个元组作为键,因为列表不起作用…)# todo: write a testfile so the example works

open("testfile.txt", "w"). write("""1,5 # matriks size

OFFENSE INVOLVING CHILDREN # key for dictionary

95 # list of value

96

35

80

100

2,2

BATTERY,THEFT

173,209 # list of tuple value

173,224""")

def strip_comment(line):

return line.split('#', 1)[0].rstrip()

mydict = {}

with open("testfile.txt") as testfile:

for line in testfile:

# first line is the next record "matrix size"

columns, rows = (int(x) for x in strip_comment(line).split(','))

# next line is the header for this record

key = tuple(strip_comment(next(testfile)).split(','))

# the next lines are the rows for this record

vals = [tuple(int(x) for x in strip_comment(next(testfile)).split(','))

for _ in range(rows)]

mydict[key] = vals

print(mydict)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值