Python: How to deal with non-subscriptable objects?
I've read a thread on what a (non)subscriptable object is but it doesn't tell me what i can do about it.
I have a code calling a mypost
private module. The aim is to set up mail accounts and to do t开发者_如何转开发his i create MailAccounts()
objects defined in the mypost
module. Quantity of accounts and their respective details are described in a configuration file. When the application starts, it collects account information and stores it in a dictionary, the structure of which is: accounts = {service : { <MailAccounts Object at xxxxx> : {username : myusername, password : mypassword}}}
where service
can be "gmail" and where MailAccounts
is the class defined in the mypost
module.
So far so good. When however i want to setup the account, i need to call its method: MailAccounts.setupAccount(username, password)
. I do this by iterating each MailAccount object of the dictionary and ask to run the method:
for service in accounts:
for account in accounts[service]:
account.setupAccount(account['username'], account['password'])
But as you may have guessed it didn't work, Python returns:
TypeError: 'MailAccount' object is not subscriptable
If i create the same account manually however it works:
account = MailAccount()
account.setupAccount('myusername', 'mypassword')
Now i believe it has something to do with the fact that my <MailAccount Object at xxxx>
is a dictionary key right? That makes it non-subscriptable (whatever that may mean)?
No what exactly does this mean to be non-subscriptable? What does it imply in this example? And of course: how can i solve / bypass this in this case?
Thanks, Benjamin :)
The way to fix it is to use dictionaries properly.
for service in accounts:
for account, creds in accounts[service].iteritems():
account.setupAccount(creds['username'], creds['password'])
The problem is that when you iterate over a dictionary, you get the keys of that dictionary, not the items.
>>> x = { 'a': 1, 'b': 2 }
>>> for item in x:
... print(item)
...
a
b
If you want to iterate over the values, do this:
>>> for item in x.values():
... print(item)
...
1
2
There is also an items
method, for both keys and values at the same time:
>>> for item in x.items():
... print(item)
...
('a', 1)
('b', 2)
精彩评论