所以我创建了一个字典,其中包含csv文件中给出的值,现在我正在尝试输入一个输入键,然后它将检查该键的字典,然后返回该值.我无法实现这个,但这就是我所拥有的,我相信我应该使用d.get(),但我不是百分之百确定.
import csv
dictionary = []
line = 0
reader = csv.reader(open("all.csv", "rb"), delimiter = ",")
header = reader.next()
for column in reader:
line = line + 1
dictionary.append({column[0]:column[2]})
print dictionary
check = raw_input("Enter word in dictionary to get its value: ")
print dictionary.get(check, "This word doesnt exist in the dictionary")
Run Code Online (Sandbox Code Playgroud)
dictionary = []
Run Code Online (Sandbox Code Playgroud)
那不是字典,而是一个列表.因此,它没有get方法.
你想要做的是像这样初始化字典:
dictionary = {}
Run Code Online (Sandbox Code Playgroud)
(注意花括号而不是方括号).同时将分配行更改为:
dictionary[column[0]] = column[2]
Run Code Online (Sandbox Code Playgroud)
那时,你的程序应该工作.