如何解决如何将CSV文件中的行存储在字典中?
我必须使用Python从CSV文件中提取索引1和5的所有行,并将它们存储在字典“名称”中。但是,由于我是Python的新手,所以我真的很难解决这个任务。这是我的代码:
names = {}
with open("../data/names.csv") as file:
for line in file:
print(line)
输出:
Id,Name,Year,Gender,State,Count
1,Mary,1910,F,AK,14
2,Annie,12
3,Anna,10
4,Margaret,8
5,Helen,7
6,Elsie,6
...
如果我尝试在字典“名称”中存储行的索引1(字符串“名称”)和行的索引5(int),则会得到错误的输出。这里的代码:
names = {}
with open("../data/names.csv") as file:
for line in file:
names = {"name": line[1],"count": line[5]}
print(names)
(错误的)输出:
{'name': '6','count': '2'}
解决方法
未指定所需的输出数据结构,我认为问题在于列(而非行)
with open('sample.csv','r') as file_handle:
file_content = file_handle.read()
list_of_dicts = []
for index,line in enumerate(file_content.split('\n')):
line_as_list = line.split(',')
if index==0:
pass # ignore the headers
else:
line_dict = {'name': line_as_list[1],'count': line_as_list[5]}
list_of_dicts.append(line_dict)
print(list_of_dicts)
如果所需的数据结构是单个字典,并且每行都有一个条目列表,
results = {'name': [],'count': []}
for index,')
if index==0:
pass # ignore the headers
else:
results['name'].append(line_as_list[1])
results['count'].append(line_as_list[5])
print(results)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。