是否存在无限嵌套的defaultdict的标准类?

Cer*_*rin 11 python dictionary nested infinite defaultdict

有谁知道Python中是否存在无限可嵌套字典的标准类?

我发现自己重复这种模式:

d = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
d['abc']['def']['xyz'] += 1
Run Code Online (Sandbox Code Playgroud)

如果我想添加"另一层"(例如d['abc']['def']['xyz']['wrt']),我必须定义另一个defaultdicts嵌套.

为了概括这种模式,我编写了一个简单的类来覆盖__getitem__自动创建下一个嵌套字典.

例如

d = InfiniteDict(('count',0),('total',0))
d['abc']['def']['xyz'].count += 0.24
d['abc']['def']['xyz'].total += 1
d['abc']['def']['xyz']['wrt'].count += 0.143
d['abc']['def']['xyz']['wrt'].total += 1
Run Code Online (Sandbox Code Playgroud)

但是,有没有人知道这个想法的预先实现?我试过谷歌搜索,但我不确定这会被称为什么.

Kat*_*iel 14

这自然适用于递归定义.

>>> import collections
>>> def nested_dd():
...     return collections.defaultdict(nested_dd)
...
>>> foo = nested_dd()
>>> foo
defaultdict(<function nested_dd at 0x023F0E30>, {})
>>> foo[1][2]=3
>>> foo[1]
defaultdict(<function nested_dd at 0x023F0E30>, {2: 3})
>>> foo[1][2]
3
Run Code Online (Sandbox Code Playgroud)


sth*_*sth 11

您可以派生defaultdict自己获得所需的行为:

class InfiniteDict(defaultdict):
   def __init__(self):
      defaultdict.__init__(self, self.__class__)

class Counters(InfiniteDict):
   def __init__(self):
      InfiniteDict.__init__(self)                                               
      self.count = 0
      self.total = 0

   def show(self):
      print "%i out of %i" % (self.count, self.total)
Run Code Online (Sandbox Code Playgroud)

这个类的用法如下所示:

>>> d = Counters()
>>> d[1][2][3].total = 5
>>> d[1][2][3].show()
0 out of 5
>>> d[5].show()
0 out of 0
Run Code Online (Sandbox Code Playgroud)


mic*_*per 9

我认为这种单线程是一个近乎完美的解决方案:

>>> from collections import defaultdict
>>> infinite_defaultdict = lambda: defaultdict(infinite_defaultdict)
>>> d = infinite_defaultdict() 
>>> d['x']['y']['z'] = 10
Run Code Online (Sandbox Code Playgroud)

作者:Raymond Hettinger在Twitter(https://twitter.com/raymondh/status/343823801278140417)

  • 这个解决方案应该排名更高! (2认同)