Вы можете попробовать использовать рекурсивный defaultdict:
from collections import defaultdict
# define a hierarchical defaultdict (of defaultdicts (of defaultdicts...))
class recursivedefaultdict(defaultdict):
def __init__(self):
self.default_factory = type(self)
# add an iterator recursively to create entries, sub-entries, etc.
def addToTree(it, v, accum):
try:
addToTree(it, v, accum[it.next()])
except StopIteration:
accum["words"] = v
# test it out
dictionary = {
4388464: ['getting'],
43881: ['got'],
827862 : ['Taruma', 'Varuna'],
}
d2 = recursivedefaultdict()
for k,v in dictionary.iteritems():
addToTree(iter(str(k)), v, d2)
# use recursion again to view the results
def dumpDict(d,indent=""):
for k,v in d.iteritems():
if k == "words":
print "%s- %s : %s" % (indent, k, v)
else:
print "%s- %s:" % (indent, k)
dumpDict(v, indent+" ")
dumpDict(d2)
Дает:
- 8:
- 2:
- 7:
- 8:
- 6:
- 2:
- words : ['Taruma', 'Varuna']
- 4:
- 3:
- 8:
- 8:
- 1:
- words : ['got']
- 4:
- 6:
- 4:
- words : ['getting']
Я думаю, рекурсивный дефолт - это прекрасный способ создать эти вложенные диктанты непредсказуемой длины. (Обратите внимание, что будут проблемы, если следующее значение, которое мы добавим, использует 43884 в качестве ключа, так как уже существует запись для d2[4][3][8][8][4]
.)