如何在字典键中允许多余的字符

时间:2013-07-25 05:35:09

标签: python dictionary

我们说我有这样的字典:

my_dict = {
           hey: onevalue,
           hat: twovalue,
           how: threevalue
           }

在有变量时,有没有办法考虑对某个键​​的引用,比如说一个数字?

例如my_dict [' hey1'] = onevalue 或my_dict [' hey2'] = onevalue

我试图允许这样的变量,而不是从引用到密钥中剥离数字。提前谢谢。

2 个答案:

答案 0 :(得分:0)

没有。由于dicts如何工作(作为hash table),他们无法满足您的需求。您必须创建自己的类型并定义__*item__()方法来实现您的逻辑。

答案 1 :(得分:0)

this answer上构建,您可以定义自己的dict兼容类型以删除尾随数字;

import collections

class TransformedDict(collections.MutableMapping):
    """A dictionary which applies an arbitrary key-altering function before accessing the keys"""

    def __init__(self, *args, **kwargs):
        self.store = dict()
        self.update(dict(*args, **kwargs)) # use the free update to set keys

    def __getitem__(self, key):
        return self.store[self.__keytransform__(key)]

    def __setitem__(self, key, value):
        self.store[self.__keytransform__(key)] = value

    def __delitem__(self, key):
        del self.store[self.__keytransform__(key)]

    def __iter__(self):
        return iter(self.store)

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

    def __keytransform__(self, key):
        for i in xrange(len(key)-1,-1,-1):
          if not key[i].isdigit():
            break
        return key[:i]

a = TransformedDict()
a['hello'] = 5
print a['hello123']

>>> 5