alfisDudas
alfisDudas

Reputation: 13

Error in access to python dictionary

I'm pretty sure that my error is a very small and stupid thing but I'm not capable to see it!! :(

I have a defined dictionary: self.names_to_nodes, and I want to access to one of its members with the key that I have.

Here is a piece of my code:

print "Result " + str(len( self.names_to_nodes))
if i in self.names_to_nodes:
    print "ESTA"
member = self.names_to_nodes.get(i)
ancestrosA.append(member.get_parent())

And I get this exit and this error:

Result 17

ESTA

143                     print "ESTA"
144                 member = self.names_to_nodes.get(i)
145                 ancestrosA.append(member.get_parent())
146                 i = member.get_parent()
147             ancestrosA.append(self.founder)

AttributeError: 'NoneType' object has no attribute 'get_parent'

How is this possible???

Thanks for your help! How get(i) is not finding the element if the key is in the dictionary?

BR, Almu

Upvotes: 1

Views: 82

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

You need to move the lookup inside the if statement if you want to make sure it exists before checking:

if i in self.names_to_nodes:
    print "ESTA"
    # only does a lookup if the key exists
    member = self.names_to_nodes[i]
    ancestrosA.append(member.get_parent())

You check if it exists but still check i outside the if so whether i exists or not you always do a lookup.

Upvotes: 2

Kevin
Kevin

Reputation: 76194

dict.get returns a value whether the key is in the dictionary or not. Example:

>>> x = {1:2}
>>> print(x.get(100))
None

Try using regular item access instead. Then your code will raise an exception if you try to get a nonexistent value. Example:

>>> x = {1:2}
>>> print(x[100])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 100

(Readers may ask, "but how could i not be a key in the dictionary? 'ESTA' was printed, and that only occurs when the membership test successfully passes". I'm assuming that this code is inside a for loop that changes the value of i, and the printed 'ESTA' is from the previous iteration, which ran without problems.)

Upvotes: 1

Related Questions