【问题标题】:Create a nested dictionary for a word python为一个单词 python 创建一个嵌套字典
【发布时间】:2013-10-28 16:19:01
【问题描述】:

我有一个单词列表,我想将它们存储在嵌套字典中。

这里是示例列表:-

words = ['Apple','Ape','Bark','Barn']

我要创建的字典如下:-

{'A':{'P':{'E':{},
           'P':{'L':{'E':{}}}}},
 'B':{'A':{'R':{'K':{},'N':{}}}}}

单词不区分大小写。

【问题讨论】:

  • 所以你想创建一个trie
  • 是的,我不知道这是一个尝试。

标签: python data-structures python-3.x


【解决方案1】:

改用collections.defaultdict() 对象:

from collections import defaultdict

def tree():
    return defaultdict(tree)

nested = defaultdict(tree)

for word in words:
    node = nested
    for char in word:
        node = node[char.upper()]

每当您尝试访问 defaultdict 中尚不存在的键时,都会调用默认工厂以透明地为该键生成值。在上面的代码中,默认工厂是tree(),它使用相同的工厂生成另一个 defaultdict(),让您只需访问键即可构建嵌套的字典集。

演示:

>>> from collections import defaultdict
>>> def tree():
...     return defaultdict(tree)
... 
>>> nested = defaultdict(tree)
>>> words = ['Apple','Ape','Bark','Barn']
>>> for word in words:
...     node = nested
...     for char in word:
...         node = node[char.upper()]
... 
>>> nested
defaultdict(<function tree at 0x114e62320>, {'A': defaultdict(<function tree at 0x114e62320>, {'P': defaultdict(<function tree at 0x114e62320>, {'P': defaultdict(<function tree at 0x114e62320>, {'L': defaultdict(<function tree at 0x114e62320>, {'E': defaultdict(<function tree at 0x114e62320>, {})})}), 'E': defaultdict(<function tree at 0x114e62320>, {})})}), 'B': defaultdict(<function tree at 0x114e62320>, {'A': defaultdict(<function tree at 0x114e62320>, {'R': defaultdict(<function tree at 0x114e62320>, {'K': defaultdict(<function tree at 0x114e62320>, {}), 'N': defaultdict(<function tree at 0x114e62320>, {})})})})})
>>> def print_nested(d, indent=0):
...     for k, v in d.iteritems():
...         print '{}{!r}:'.format(indent * '  ', k)
...         print_nested(v, indent + 1)
... 
>>> print_nested(nested)
'A':
  'P':
    'P':
      'L':
        'E':
    'E':
'B':
  'A':
    'R':
      'K':
      'N':

defaultdict 是标准 Python 字典的子类,除了自动实现键值外,其行为与常规字典完全相同。

【讨论】:

  • 感谢您提供帮助。如果您能告诉我一种有效的遍历方法,我也将不胜感激,这样我就可以检查以“bar”开头的单词。
  • 我之前写过遍历嵌套管道;有关示例,请参见 stackoverflow.com/a/14692747stackoverflow.com/a/17797566
猜你喜欢
  • 2012-02-10
  • 1970-01-01
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2020-07-29
  • 2023-01-18
相关资源
最近更新 更多