Python创建自己的字典子集的dict视图 [英] Python create own dict view of subset of dictionary

查看:246
本文介绍了Python创建自己的字典子集的dict视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于关于这个SO的这个主题的许多问题证明,采取一个字典是一个很常见的任务,有一个相当不错的解决方案:

  {k:v for k,v in dict.viewitems()if some_test(k,v)} 

但是,它创建一个新的字典,具有自己的映射。对于许多操作,只要拥有原始dict的不可变视图(即它不支持在视图上的分配或删除操作),这将是很好的。实现这种类型可能很容易,但是增加本地实用程序类并不好。



所以,我的问题是:是有一种内置的获取这种子集视图的方法?还是有一个第三方库(最好是通过PyPi提供),可以很好地实现这样一个实用程序?

解决方案

似乎没有内置的方式来获取一个字典的视图。最容易的解决方法似乎是Jochen的做法。我修改了他的代码,以使其适用于我的目的:

 从集合导入MutableMapping 

类DictView(MutableMapping):
def __init __(self,source,valid_keys):
self.source,self.valid_keys = source,valid_keys

def __getitem __(self,key)
如果key in self.valid_keys:
return self.source [key]
else:
raise KeyError(key)

def __len __(self) :
return len(self.valid_keys)

def __iter __(self):
for key in self.valid_keys:
yield key

def __setitem __(self,key,value):
如果键入self.valid_keys:
self.source [key] = value
else:
raise KeyError(key)

def __delitem __(self,key):
self.valid_keys.remove(key)

d = dict(a = 1,b = 2,c = 3)
valid_keys = ['a','c']
d2 = DictVi ew(d,valid_keys)
d2 ['a'] = -1#在源字典中覆盖元素'a'
print d#prints {'a':-1,'c':3, 'b':2}

所以 d2 由于不同的 __ repr __()方法,所以除了打印外,其他方面的行为都像字典。继承 dict 以获得 __ repr __()将需要重新实现每种方法,如 collections.OrderedDict 。如果只想要一个只读的视图,可以继承 collections.Mapping 并保存 __ setitem __()的实现, __ delitem __()。我发现 DictView 可用于从 self .__ dict __ 中选择参数,并以紧凑形式传递它们。


As the many questions on the topic here on SO attest, taking a slice of a dictionary is a pretty common task, with a fairly nice solution:

{k:v for k,v in dict.viewitems() if some_test(k,v)}

But that creates a new dictionary, with its own mappings. For many operations, it would be nice to just have an immutable view of the original dict (i.e. it does not support assignment or deletion operations on the view). Implementing such a type is probably easy, but it's not good to have a proliferation of local utility classes.

So, my question is: is there a built-in way of obtaining such a "subset view"? Or is there a third-party library (preferably available via PyPi) that provides a good implementation of such a utility?

解决方案

There seems to be no builtin way to obtain a view into a dictionary. The easiest workaround appears to be Jochen's approach. I adapted his code slightly to make it work for my purposes:

from collections import MutableMapping

class DictView(MutableMapping):
    def __init__(self, source, valid_keys):
        self.source, self.valid_keys = source, valid_keys

    def __getitem__(self, key):
        if key in self.valid_keys:
            return self.source[key]
        else:
            raise KeyError(key)

    def __len__(self):
        return len(self.valid_keys)

    def __iter__(self):
        for key in self.valid_keys:
            yield key

    def __setitem__(self, key, value):
        if key in self.valid_keys:
            self.source[key] = value
        else:
            raise KeyError(key)

    def __delitem__(self, key):
        self.valid_keys.remove(key)

d = dict(a=1, b=2, c=3)
valid_keys = ['a', 'c']
d2 = DictView(d, valid_keys)
d2['a'] = -1  # overwrite element 'a' in source dictionary
print d  # prints {'a': -1, 'c': 3, 'b': 2}

So d2 behaves like a dictionary in all aspects except for printing, due to the different __repr__() method. Inheriting from dict to get __repr__() would require reimplementation of each and every method, as is done for collections.OrderedDict. If one wants only a readonly view, one can inherit from collections.Mapping and save the implementation of __setitem__() and __delitem__(). I find DictView useful to select parameters from self.__dict__ and pass them on in a compact form.

这篇关于Python创建自己的字典子集的dict视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆