我不确定我的 user_dictionary 出了什么问题。我创建了 get 方法 ot check 并确保它正确上传。键设置为用户名,我希望每个键都等于评级值列表。正如您在终端中看到的那样,键似乎加载得很好,但是当我调用查看特定键值时,我收到此错误([] 有人知道这是什么意思吗?我还添加了我正在加载的文件到 user_dictionary 所以你可以看到布局。
我正在上传的文件的 1 行
本,5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0
以不同的名称作为第一个单词,依此类推
def read_users(user_file_name):
returnDict={}
try:
f = open(user_file_name,"r")
for line in f:
temp=line.split(',')
a=temp[0]
#returnDict[a]=[]
temp.pop(0)
value= map(int, temp)
returnDict[a]=[value]
return returnDict;
except:
return;
类库:
def __init__(self,books_filename,ratings_filename):
self.book_list = read_books(books_filename)
self.user_dictionary = read_users(ratings_filename)
def getUser_Dictionary(self):
#print(self.user_dictionary.keys())
print(self.user_dictionary['nathan'])
最佳答案
您没有收到错误,而是您的值的空列表。这是因为您将值设置为 map 对象,而不是您想要的值。
替换这些行:
value= map(int, temp)
returnDict[a]=[value]
和:
value = list(map(int, temp))
returnDict[a] = value
returnDict 也是一个非常令人困惑的变量名,我会避免使用它。
关于python - 将文件加载到字典时出现奇怪的python错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50162260/