2016-10-18 86 views
-1

是否可以從字典中刪除值而不是密鑰?例如, 我有以下代碼,其中用戶選擇與他想要刪除它的元素對應的鍵,但我只想刪除該值而不是鍵(該值是一個列表):Python從字典中刪除值而不是密鑰

if (selection == 2): 
    elem = int(input("Please select the KEY that you want to be deleted: ")) 
    if dictionar.has_key(elem): 
     #dictionar.pop(elem) 
     del dictionar[elem] 
    else: 
     print("the KEY is not present ") 
+3

如果你什麼'dictionar [ELEM] = None' –

+1

'has_key'已被棄用。使用'elem in dictionar'。 –

+0

只需設置等於None常量的值。 – Frogboxe

回答

4

不,這是不可能的。字典由鍵/值對組成。沒有價值,你不能擁有一把鑰匙。您可以做的最好的方法是將該密鑰的值設置爲None或其他一些哨點值,或者使用更適合您需求的不同數據結構。

-1
dictionar = {} 
elem = int(input("Please select the KEY that you want to be deleted: ")) 
if dictionar.has_key(elem) 
    dictionar[elem] = "" 
else: 
    print("The KEY is not present") 

此代碼檢查elem是否在詞典中,然後將該值變成空白字符串。

0

字典是具有{key:value}對的數據結構。

要與價值觀工作,你可以做一些其它的值或None替換值象下面這樣:

dic = {} 
e = int(input("KEY to be deleted/replaced: "))  

if dic.has_key(e): 
    r = int(input("New value to put in or just press ENTER for no new value")) 
    if not r: 
     r=None 
    dic[e]=r 
else: 
    print("Key Absent") 
相關問題