从CSV文件创建字典

从CSV文件创建字典,第1张

从CSV文件创建字典

创建一个字典,然后遍历结果并将行填充到字典中。请注意,如果遇到日期重复的行,则必须决定要执行的 *** 作(引发异常,替换上一行,丢弃下一行等)。

这是test.csv:

Date,Foo,Bar123,456,789abc,def,ghi

和相应的程序:

import csvreader = csv.reader(open('test.csv'))result = {}for row in reader:    key = row[0]    if key in result:        # implement your duplicate row handling here        pass    result[key] = row[1:]print(result)

产量:

{'Date': ['Foo', 'Bar'], '123': ['456', '789'], 'abc': ['def', 'ghi']}

或者,使用DictReader:

import csvreader = csv.DictReader(open('test.csv'))result = {}for row in reader:    key = row.pop('Date')    if key in result:        # implement your duplicate row handling here        pass    result[key] = rowprint(result)

结果是:

{'123': {'Foo': '456', 'Bar': '789'}, 'abc': {'Foo': 'def', 'Bar': 'ghi'}}

或者,您可能希望将列标题映射到该列的值列表:

import csvreader = csv.DictReader(open('test.csv'))result = {}for row in reader:    for column, value in row.items():  # consider .iteritems() for Python 2        result.setdefault(column, []).append(value)print(result)

产生:

{'Date': ['123', 'abc'], 'Foo': ['456', 'def'], 'Bar': ['789', 'ghi']}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5632080.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存