Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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}
like image 423
edg Avatar asked Mar 13 '12 13:03

edg


2 Answers

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.

like image 166
wim Avatar answered Nov 13 '22 21:11

wim


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]
like image 28
interjay Avatar answered Nov 13 '22 21:11

interjay