简体   繁体   中英

How to delete just one key from a python dictionary?

I am creating a dictionary, that potentially has keys that are the same, but the values of each key are different. Here is the example dict:

y = {44:0, 55.4:1, 44:2, 5656:3}
del y[44]
print y
{5656: 3, 55.399999999999999: 1}

I would like to be able to do something like:

 del y[44:0]

Or something of that nature.

You never had duplicate keys:

>>> y = {44:0, 55.4:1, 44:2, 5656:3}
>>> y
{5656: 3, 55.4: 1, 44: 2}

A dictionary can be initialised with duplicate keys, but all but one will be ignored.

Just an idea- instead of having scalar values, why not a collection of some kind? Perhaps even a set if they are unique values:

myDict = {44:set([1, 2, 3])}

So to add or remove an object:

myDict[44].add(1)
myDict[44].remove(1)

For adding a new key:

if newKey not in myDict:
    myDict[newKey] = set() # new empty set

Your question is moot. In your y declaration, the 44:2 wouldn't go alongside 44:0 , it would overwrite it. You'd need to use a different key if you want both values in the dictionary.

Before deleting:--

>>>dic={"a":"A","b":"B","c":"C","d":"D","e":"E"}

>>> del dic['a'] 

after deleting :-

>>>dic
{'b': 'B','c': 'C','d': 'D','e': 'E'}

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