我目前需要一个类似于内置dict
类型的类似功能的Python容器类。基本上我需要的是一个字典,其中主键旁边的任意数量的键,映射到相同的值。但是,当迭代它时,它应该仅在(primary_key, value)
对上迭代,如果请求键列表,则仅迭代主键。
如果这已经实施,我宁愿不重新发明轮子。那么是否有一个模块提供这样的容器?如果没有,我将自己实施。
答案 0 :(得分:2)
这是一个快速实施:
class MultipleKeyDict(dict):
__slots__ = ["_primary_keys"]
def __init__(self, arg=None, **kwargs):
self._primary_keys = {}
self.update(arg, **kwargs)
def __setitem__(self, key, value):
super(MultipleKeyDict, self).__setitem__(key, value)
self._primary_keys.setdefault(value, key)
def __delitem__(self, key):
value = self[key]
super(MultipleKeyDict, self).__delitem__(key)
if self._primary_keys[value] == key:
del self._primary_keys[value]
for k, v in super(MultipleKeyDict, self).iteritems():
if v == value:
self._primary_keys[value] = k
break
def __iter__(self):
return self.iterkeys()
def update(self, arg=None, **kwargs):
if arg is not None:
if isinstance(arg, collections.Mapping):
for k in arg:
self[k] = arg[k]
else:
for k, v in arg:
self[k] = v
for k in kwargs:
self[k] = kwargs[k]
def clear(self):
super(MultipleKeyDict, self).clear()
self._primary_keys.clear()
def iteritems(self):
for v, k in self._primary_keys.iteritems():
yield k, v
def items(self):
return list(self.iteritems())
def itervalues(self):
return self._primary_keys.iterkeys()
def values(self):
return self._primary_keys.keys()
def iterkeys(self):
return self._primary_keys.itervalues()
def keys(self):
return self._primary_keys.values()
唯一令人讨厌的一点是它必须搜索整个dict以防主键被删除。
我省略了copy()
,pop()
,popitem()
和setdefault()
。如果你需要它们,你必须自己实现它们。
答案 1 :(得分:1)
最简单和最简单的解决方案是使用两个词典,其中一个将辅助键映射到主键。如果由于某种原因需要反向映射,则可以将其包含在主字典中。
sec = {'one': 'blue', 'two': 'red', 'three': 'blue', # seconary keys
'blue': 'blue', 'red': 'red'} # include identity mapping for primaries
dict = {'blue': ('doll', '$9.43', ('one', 'three')),
'red': ('truck', '$14.99', ('two',)) }
record = dict[sec['two']]
print('Toy=', record[0], 'Price=', record[1])
答案 2 :(得分:0)
现在有一个多关键字典python包。
https://pypi.python.org/pypi/multi_key_dict/1.0.2
从链接:
from multi_key_dict import multi_key_dict k = multi_key_dict() k[1000, 'kilo', 'k'] = 'kilo (x1000)' print k[1000] # will print 'kilo (x1000)' print k['k'] # will also print 'kilo (x1000)' # the same way objects can be updated, deleted: # and if an object is updated using one key, the new value will # be accessible using any other key, e.g. for example above: k['kilo'] = 'kilo' print k[1000] # will now print 'kilo' as value was updated