2011-04-28 60 views
-1
arguments=dict() 
if (arg.find("--help") == 0): 
    arguments["help"] = 1 
if help in arguments: 
    #this doesnt work 

print(arguments["help"]) # This will print 1 

無法確定某個鍵是否已被定義。 .has_key在2.7中已被棄用,我還沒有找到其他解決方案。我究竟做錯了什麼?Python:鍵是否存在於字典中(Python 3.1)

+2

如果你解析參數,爲什麼不使用'optparse'? (http://docs.python.org/library/optparse.html) – jathanism 2011-04-28 18:44:48

+2

optparse已被argparse取代,它將在Python的未來版本中維護(儘管目前我不認爲存在非常大的差異) 。我相信它支持2.7+和3.2+。 – 2011-04-28 19:27:17

回答

8

只要做"help" in arguments

>>> arguments = dict() 
>>> arguments["help"]=1 
>>> "help" in arguments 
True 

在你的榜樣,你已經寫help in arguments沒有字符串引號包圍。因此它假定詢問內置函數help是否是您的字典中的一個關鍵字。

另外請注意,你可以寫arguments = {}作爲創建字典更pythonic的方式。

3

你忘了援引引號。因爲幫助是內建的,python並不像通常那樣抱怨。