简体   繁体   English

从字典中检索信息

[英]Retrieving information from dictionary

I'm having hard time trying to read my dictionary variable. 我很难读取我的字典变量。 Python keeps throwing the following error: Python不断抛出以下错误:

TypeError: string indices must be integers

This is a sample that should give you an idea of what my problem is: 这是一个示例,应该使您了解我的问题是:

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 ...

This is all I get as a Traceback: 这就是我作为追溯获得的一切:

user_id = self.dict['userID']
TypeError: string indices must be integers

No I'm positive that self.dict is not a string. 不,我肯定self.dict不是字符串。

It's being created in a function called createUser and it's being returned to the main thread. 它是在名为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

After that self.dict is only referenced for reading data from it. 之后,仅引用self.dict读取数据。

I've found the problem, and it was in my signal definition. 我发现了问题,这在我的信号定义中。 Dictionary 'self.dict' is being returned via pyqtSignal which was defined like this: 字典'self.dict'通过pyqtSignal返回,其定义如下:

addUser = pyqtSignal(object)

After thorough examination of my code I've figured out that I should change it to: 仔细检查我的代码后,我发现应该将其更改为:

addUser = pyqtSignal(dict)

and once I did that it was all right. 一旦我做到了,那就好了。 Once again, thanks everyone for their contribution. 再次感谢大家的贡献。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM