How to remove a key from the dictionary with the highest value?

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

I have a dictionary, let's say it looks like this:

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

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

 del max(dict.values()) 

and this error message is: "Syntax error: do not delete function call." I want the final result:

 dict = {'a':10, 'T':50, 't':5} 
+6
source share
2 answers

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

You can do it:

 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 should not call the dictionary dict , because it is a name of a built-in type.

If there can be several records 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] 
+9
source

You need to keep the key from the maximum value.

Try this instead:

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

In addition, you should avoid calling the dict variable, as it obscures the built-in name.

+8
source

Source: https://habr.com/ru/post/910599/


All Articles