从字典中弹出键值 PAIR 的巧妙方法?

Neat way of popping key, value PAIR from dictionary?

pop 是一个很棒的小函数,当在字典上使用时(给定一个已知键)从字典中删除具有该键的项目以及 returns 相应的值。但是,如果我也想要钥匙怎么办?

显然,在简单的情况下,我可能会做这样的事情:

pair = (key, some_dict.pop(key))

但是,假设我想弹出具有最低值的键值对,按照上面的想法我将不得不这样做...

pair = (min(some_dict, key=some.get), some_dict.pop(min(some_dict, key=some_dict.get)))

... 这太可怕了,因为我必须执行两次操作(显然我可以将 min 的输出存储在一个变量中,但我仍然对此并不完全满意)。所以我的问题是:有没有一种优雅的方法可以做到这一点?我在这里错过了一个明显的技巧吗?

堆支持你描述的pop-min操作。不过,您需要先从字典创建一个堆。

import heapq
# Must be two steps; heapify modifies its argument in-place.
# Reversing the key and the value because the value will actually be
# the "key" in the heap. (Or rather, tuples are compared 
# lexicographically, so put the value in the first position.)
heap = [(v, k) for k, v in some_dict.items()]
heapq.heapify(heap)

# Get the smallest item from the heap
value, key = heapq.heappop(heap)

您可以使用 python ABCs which provides the infrastructure for defining abstract base classes 定义自己的字典对象。然后根据需要重载 python 字典对象的 pop 属性:

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__)

演示:

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}

注意 :正如@chepner 在评论中建议的更好的选择,您可以覆盖 popitem,它已经 returns 一对 key/value .

这里有一个更简单的实现

class CustomDict(dict):
    def pop_item(self, key):
        popped = {key:self[key]} #save "snapshot" of the value of key before popping
        self.pop(key)
        return popped

a = CustomDict()
b = {"hello":"wassup", "lol":"meh"}
a.update(b)
print(a.pop_item("lol"))
print(a)

所以在这里我们创建一个自定义 dict 弹出你想要的项目并给出 key-value 对