1

我正在尝试从 python 中的 csv 文件制作字典,但我有多个类别。我希望键是 ID 号,值是项目的名称。这是文本文件:

"ID#","name","quantity","price"
"1","hello kitty","4","9999"
"2","rilakkuma","3","999"
"3","keroppi","5","1000"
"4","korilakkuma","6","699"

这就是我到目前为止所拥有的:

txt = open("hk.txt","rU")

file_data = txt.read()
lst = []           #first make a list, and then convert it into a dictionary.
for key in file_data:
        k = key.split(",")
        lst.append((k[0],k[1]))

dic = dict(lst)
print(dic)

不过,这只是打印一个空列表。我希望键是 ID#,然后值将是产品的名称。我将制作另一个字典,名称为键,ID# 为值,但我认为这将是同一件事,但反过来。

4

4 回答 4

3

使用该csv模块来处理您的数据;它将删除引用并处理拆分:

results = {}

with open('hk.txt', 'r', newline='') as txt:
    reader = csv.reader(txt)
    next(reader, None)  # skip the header line
    for row in reader:
        results[row[0]] = row[1]

对于您的示例输入,这会产生:

{'4': 'korilakkuma', '1': 'hello kitty', '3': 'keroppi', '2': 'rilakkuma'}
于 2013-07-25T15:41:16.063 回答
2

您可以使用csv DictReader

import csv

result={}
with open('/tmp/test.csv', 'r', newline='') as f:
    for d in csv.DictReader(f):
        result[d['ID#']]=d['name']

print(result)
# {'1': 'hello kitty', '3': 'keroppi', '2': 'rilakkuma', '4': 'korilakkuma'}
于 2013-07-26T00:18:35.990 回答
1

您可以直接使用字典:

dictionary = {}
file_data.readline()   # skip the first line         
for key in file_data:
    key = key.replace('"', '').strip()
    k = key.split(",")
    dictionary[k[0]] = k[1]
于 2013-07-25T15:41:45.137 回答
0

试试这个或使用任何库来读取文件。

txt = open("hk.txt","rU")

file_data = txt.read()
file_lines = file_data.split("\n")
lst = []           #first make a list, and then convert it into a dictionary.
for linenumber in range(1,len(file_lines)):
        k = file_lines[linenumber].split(",")
        lst.append((k[0][1:len(k[0])-1],k[1][1:len(k[1])-1]))

dic = dict(lst)
print(dic)

但你也可以直接使用字典。

于 2013-07-25T15:48:57.707 回答