【发布时间】:2015-12-30 11:38:13
【问题描述】:
我很难阅读我的字典变量。 Python不断抛出以下错误:
TypeError: string indices must be integers
这是一个示例,可以让您了解我的问题是什么:
self.dict = {}
self.dict['User'] = 'User_name'
self.dict['Dir'] = 'user_home_dir'
self.dict['userID'] = 1
if self.dict['userID'] == 1: # this is the line that is said to contain an error
then do somethin ...
这就是我作为 Traceback 得到的全部内容:
user_id = self.dict['userID']
TypeError: string indices must be integers
不,我很肯定self.dict 不是字符串。
它在一个名为 createUser 的函数中被创建,并被返回到主线程。
def createUser(self):
self.dict = {}
... user inputs information ...
... and then information is inserted into self.dict ...
self.dict['User'] = self.lineEdit_User.text()
self.dict['Dir'] = self.lineEdit_path.text()
self.dict['userID'] = int(self.lineEdit_ID.text())
return self.dict
之后,self.dict 仅用于从中读取数据。
【问题讨论】:
-
你有
self.dict = {},然后你使用dict,你提供的也没有任何东西会导致你的错误 -
很抱歉,这是一个错字。我编辑了示例代码以更准确地表示我的问题。我一直在尝试,似乎解释器没有将“userID”视为数字。这就是我收到此错误消息的原因。但是我看不到解决此问题的方法。
-
您的错误表明您正在执行类似
"foo"["abc"]的操作,而不是查找字典,请添加完整的回溯。 -
我添加了完整的回溯。也许我应该提到我正在线程内的 self.dict 中设置“userID”值。我不认为这应该是一个问题。
-
self.dict是一个 str 而不是一个字典,如果它曾经指向一个字典,你已经在某处重新分配了名称
标签: python python-3.x dictionary