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}
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With