Jr.
Jr.

Reputation: 111

Beginner Python: Checking Membership In Dictionary and Using Decision Structures

I was working on code and ran across an issue where I'm trying to use an if-statement based on if user input is found in a dictionary. For example lets say if a user wants to find a name in an address book and I save their response to a variable "findName" which is the key for the dictionary. Let's also say the dictionary name is "contact".

if contact.has_key[findName] == True: 
    #Do something here. 
elif contact.has_key[findName] == False: 
    #Do something else.

The problem is that every time I do this, I get an error message saying: 'builtin_function_or_method' object has no attribute 'getitem'.

I don't really know where my code went wrong, can someone guide me to the correct answer and explanation?

Upvotes: 0

Views: 76

Answers (2)

GWW
GWW

Reputation: 44141

You aren't calling the has_key method.

It should be

if contact.has_key(findName) == True: 
    #Do something here. 
elif contact.has_key(findName) == False: 
    #Do something else.

A more pythonic way to do this is to use in and you don't need to check for the False condition you can use use else.

if findName in contact: 
    #Do something here. 
else: 
    #Do something else.

Upvotes: 3

Christian Ternus
Christian Ternus

Reputation: 8492

You have a syntax error. There shouldn't be a colon after elif, and has_key is a method:

if contact.has_key(findName) == True: 
    #Do something here. 
elif contact.has_key(findName) == False: 
    #Do something else.

But this, of course, can just be reduced to:

if contact.has_key(findName): 
    #Do something here. 
else:
    #Do something else.

Upvotes: 2

Related Questions