簡體   English   中英

如何將 CSV 文件中的行存儲在字典中?

[英]How can I store lines from a CSV file in a dictionary?

我必須使用 Python 從 CSV 文件中提取索引 1 和 5 處的所有行並將它們存儲在字典“名稱”中。 但是,由於我是 Python 的新手,我真的很努力完成這項任務。 這是我的代碼:

names = {}
with open("../data/names.csv") as file:
    for line in file:
        print(line)

output:

Id,Name,Year,Gender,State,Count
1,Mary,1910,F,AK,14
2,Annie,1910,F,AK,12
3,Anna,1910,F,AK,10
4,Margaret,1910,F,AK,8
5,Helen,1910,F,AK,7
6,Elsie,1910,F,AK,6
...

如果我嘗試在字典“names”中存儲行的索引 1(字符串“Name”)和索引 5(int),則會得到錯誤的 output。 這里的代碼:

names = {}
with open("../data/names.csv") as file:
    for line in file:
        names = {"name": line[1], "count": line[5]}
print(names)

(錯誤的)output:

{'name': '6', 'count': '2'}

未指定所需的 output 數據結構,我認為問題是關於列(不是行)

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, line in enumerate(file_content.split('\n')):
    line_as_list = line.split(',')
    if index==0:
        pass # ignore the headers
    else:
        results['name'].append(line_as_list[1])
        results['count'].append(line_as_list[5])
print(results)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM