python - Neat way of popping key, value PAIR from dictionary? -
pop
great little function that, when used on dictionaries (given known key) removes item key dictionary , returns corresponding value. if want key well?
obviously, in simple cases this:
pair = (key, some_dict.pop(key))
but if, say, wanted pop key-value pair lowest value, following above idea have this...
pair = (min(some_dict, key=some.get), some_dict.pop(min(some_dict, key=some_dict.get)))
... hideous have operation twice (obviously store output min
in variable, i'm still not happy that). question is: there elegant way this? missing obvious trick here?
you can define dictionary object using python abcs provides infrastructure defining abstract base classes. , overload pop
attribute of python dictionary objects based on need:
from collections import mapping class mydict(mapping): def __init__(self, *args, **kwargs): self.update(dict(*args, **kwargs)) def __setitem__(self, key, item): self.__dict__[key] = item def __getitem__(self, key): return self.__dict__[key] def __delitem__(self, key): del self.__dict__[key] def pop(self, k, d=none): return k,self.__dict__.pop(k, d) def update(self, *args, **kwargs): return self.__dict__.update(*args, **kwargs) def __iter__(self): return iter(self.__dict__) def __len__(self): return len(self.__dict__) def __repr__(self): return repr(self.__dict__)
demo:
d=mydict() d['a']=1 d['b']=5 d['c']=8 print d {'a': 1, 'c': 8, 'b': 5} print d.pop(min(d, key=d.get)) ('a', 1) print d {'c': 8, 'b': 5}
note : @chepner suggested in comment better choice can override popitem
, returns key/value pair.
Comments
Post a Comment