使用以下课程
from collections import defaultdict, OrderedDict
class NestedOrderedDict(OrderedDict):
def __missing__(self,k):
val = self[k] = NestedOrderedDict()
return self[k]
我尝试制作有序列表的
orddodol = NestedOrderedDict()
orddodol["foo"]["a"].append(1)
orddodol["foo"]["b"].append(1)
orddodol["foo"]["b"].append(12)
orddodol["bar"]["a"].append(2)
orddodol["bar"]["a"].append(3)
但它没有给出
AttributeError: 'NestedOrderedDict' object has no attribute 'append'
做正确的方法是什么?
答案 0 :(得分:4)
您必须将二级字典值初始化为列表:
from collections import defaultdict, OrderedDict
class NestedOrderedDict(OrderedDict):
def __missing__(self,k):
val = self[k] = NestedOrderedDict()
return self[k]
orddodol = NestedOrderedDict()
orddodol["foo"]["a"] = [] # these
orddodol["foo"]["b"] = [] # three
orddodol["bar"]["a"] = [] # lines
orddodol["foo"]["a"].append(1)
orddodol["foo"]["b"].append(1)
orddodol["foo"]["b"].append(12)
orddodol["bar"]["a"].append(2)
orddodol["bar"]["a"].append(3)
答案 1 :(得分:4)
你几乎做对了:)如果你想创建列表字典的有序字典,那么你最好为此目的使用defaultdict(list)
:
from collections import defaultdict, OrderedDict
class NestedOrderedDict(OrderedDict):
def __missing__(self, k):
>>>> self[k] = defaultdict(list)
return self[k]
orddodol = NestedOrderedDict()
orddodol["foo"]["a"].append(1)
orddodol["foo"]["b"].append(1)
orddodol["foo"]["b"].append(12)
orddodol["bar"]["a"].append(2)
orddodol["bar"]["a"].append(3)
答案 2 :(得分:1)
from collections import defaultdict, OrderedDict
class NestedOrderedDict(OrderedDict):
def __missing__(self,k):
val = self[k] = NestedOrderedDict()
return self[k]
orddodol = NestedOrderedDict()
orddodol["foo"]["a"] = []
orddodol["foo"]["b"] = []
orddodol["bar"]["a"] = []
orddodol["foo"]["a"].append(1)
orddodol["foo"]["b"].append(1)
orddodol["foo"]["b"].append(12)
orddodol["bar"]["a"].append(2)
orddodol["bar"]["a"].append(3)
或者您可以按照此帖Can I do an ordered, default dict in Python
的顺序实现defaultdictfrom collections import OrderedDict, Callable
class DefaultOrderedDict(OrderedDict):
# Source: https://stackoverflow.com/a/6190500/562769
def __init__(self, default_factory=None, *a, **kw):
if (default_factory is not None and
not isinstance(default_factory, Callable)):
raise TypeError('first argument must be callable')
OrderedDict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return OrderedDict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory is None:
args = tuple()
else:
args = self.default_factory,
return type(self), args, None, None, self.items()
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
def __deepcopy__(self, memo):
import copy
return type(self)(self.default_factory,
copy.deepcopy(self.items()))
def __repr__(self):
return 'OrderedDefaultDict(%s, %s)' % (self.default_factory,
OrderedDict.__repr__(self))