简体   繁体   中英

how to delete a key from a dictionary with the highest value?

I have a simple question (or so I thought).

I have a dictionary, lets say it looks like this:

dict = {'A':100, 'a':10, 'T':50, 't':5}

I simply want to delete the key with the highest value. I tried this:

del max(dict.values())

and this is the error message: 'Syntax Error: can´t delete function call'. I want the end result to be:

dict = {'a':10, 'T':50, 't':5}

max(d.values()) will give you the maximum value (100), but to delete an entry from a dictionary you need the corresponding key ( 'A' ).

You can do this:

d = {'A':100, 'a':10, 'T':50, 't':5}
key_to_delete = max(d, key=lambda k: d[k])
del d[key_to_delete]

By the way, you shouldn't name your dictionary dict because that's the name of a built-in type.

If there may be multiple entries with the same maximum value and you want to delete all of them:

val_to_delete = max(d.values())
keys_to_delete = [k for k,v in d.iteritems() if v==val_to_delete]
for k in keys_to_delete:
    del d[k]

You need to get a hold of the key to the max value.

Try this instead:

del d[max(d, key=d.get)]

Also, you should avoid calling your variable dict because it shadows the built-in name.

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