简体   繁体   中英

Python delete a value from dictionary and not the key

Is it possible to delete a value from a dictionary and not the key? For instance, I have the following code in which the user selects the key corresponding to the element that he wants to delete it , but I want do delete only the value and not the key ( the value is a list):

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 ")

No, it is not possible. Dictionaries consist of key/value pairs. You cannot have a key without a value. The best you can do is set that key's value to None or some other sentinel value, or use a different data structure that better suits your needs.

Dictionaries are data structures with {key:value} pairs.

To work with values, you can do replace the value with some other value or None like below:

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")
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")

This code checks if elem is in dictionar then turns the value into a blank string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM