简体   繁体   English

弹出键的整洁方式,从字典中值PAIR吗?

[英]Neat way of popping key, value PAIR from dictionary?

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. pop是一个很棒的小功能,当用在字典上(已知键)时,它会从字典中删除带有该键的项目,并返回相应的值。 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). ...这很可怕,因为我必须两次执行该操作(显然,我可以将min的输出存储在一个变量中,但是我对此并不完全满意)。 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. 堆支持您描述的pop-min操作。 You'll need to create a heap from your dictionary first, though. 不过,您首先需要根据字典创建一个堆。

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)

You can define yourself dictionary object using python ABC s which provides the infrastructure for defining abstract base classes . 您可以使用python ABC定义自己的字典对象,该对象提供了用于定义抽象基类的基础结构。 And then overload the pop attribute of python dictionary objects based on your need: 然后根据需要重载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__)

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. 注意 :如@chepner在注释中建议的更好的选择,您可以覆盖popitem ,它已经返回了键/值对。

here is a simpler implementation 这是一个更简单的实现

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)

So here we create a custom dict that pops the item you want and gives out the key-value pair 因此,在这里我们创建一个自定义dict ,弹出您想要的项目并给出键值对

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM