当前位置: 动力学知识库 > 问答 > 编程问答 >

AttributeError when checking if a key exist in a dictionary, using python

问题描述:

I am using Python 2.7.2+, and when trying to see if a dictionary holds a given string value (named func) I get this exception:

Traceback (most recent call last):

File "Translator.py", line 125, in <module>

elif type == Parser.C_ARITHMETIC : parseFunc()

File "Translator.py", line 95, in parseFunc

if unary.has_key(func) :

AttributeError: 'function' object has no attribute 'has_key'

This is where I define the dictionaries:

binary = {"add":'+', "sub":'-', "and":'&', "or":'|'}

relational = {"eq":"JEQ" , "lt":"JLT", "gt":"JGT"}

unary = {"neg":'-'}

Here's the function where the exception is raised:

def parseFunc():

func = parser.arg1

print func

output.write("//pop to var1" + endLine)

pop(var1)

if unary.has_key(func) : // LINE 95

unary()

return

output.write("//pop to var2" + endLine)

pop(var2)

result = "//"+func + endLine

result += "@" + var1 + endLine

result += "D=M" + endLine

result += "@" + var2 + endLine

output.write(result)

if binary.has_key(func) :

binary()

else : relational()

Also, I tried changing if unary.has_key(func) to if func in unary but then I got

Traceback (most recent call last):

File "Translator.py", line 126, in <module>

elif type == Parser.C_ARITHMETIC : parseFunc()

File "Translator.py", line 95, in parseFunc

if func in unary:

TypeError: argument of type 'function' is not iterable

P.s I tired it also using python 3.2

Any ideas? Thanks

网友答案:

In Python 3, dict.has_key() is gone (and it has been deprecated for quite some time). Use x in my_dict instead.

Your problem is a different one, though. While your definition shows unary should be a dictionary, the traceback shows it actually is a function. So somewhere in the code you did not show, unary is redefined.

And even if unary was a dictionary, you would not be able to call it.

网友答案:

It seems from your trace that you override the value of unary with a function (do you have any function called "unary"?). Therefore you are trying to call "has_key" method on a function that obviously has no such method. Pay attention with variable names, variable x will override def x() if it's placed after it in your code, and vice versa.

分享给朋友:
您可能感兴趣的文章:
随机阅读: