pop
is a great little function that, when used on dictionaries (given a known key) removes the item with that key from the dictionary and also returns the corresponding value. But what if I want the key as well?
Obviously, in simple cases I could probably just do something like this:
pair = (key, some_dict.pop(key))
But if, say, I wanted to pop the key-value pair with the lowest value, following the above idea I would have to do this...
pair = (min(some_dict, key=some.get), some_dict.pop(min(some_dict, key=some_dict.get)))
... which is hideous as I have to do the operation twice (obviously I could store the output from min
in a variable, but I'm still not completely happy with that). So my question is: Is there an elegant way to do this? Am I missing an obvious trick here?
A heap supports the pop-min operation you describe. You'll need to create a heap from your dictionary first, though.
here is a simpler implementation
So here we create a custom
dict
that pops the item you want and gives out the key-value pairYou can define yourself dictionary object using python ABCs which provides the infrastructure for defining abstract base classes. And then overload the
pop
attribute of python dictionary objects based on your need:Demo:
Note : As @chepner suggested in comment as a better choice you can override
popitem
, which already returns a key/value pair.