Neat way of popping key, value PAIR from dictionary?

后端 未结 3 1354
粉色の甜心
粉色の甜心 2021-01-18 03:20

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 corre

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-18 04:15

    You 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:

    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 : As @chepner suggested in comment as a better choice you can override popitem, which already returns a key/value pair.

提交回复
热议问题