2024-10-02 00:35:22 发布
网友
我想翻一下下面的字典:
dictionary = { 4388464: ['getting'] 827862 : ['Taruma', 'Varuna'] ... }
进入:
这样我就可以使用字典了,比如:dictionary[8][2][7][8][6][2]['words']而不是:dictionary[827862]。在
dictionary[8][2][7][8][6][2]['words']
dictionary[827862]
制作字典的简短解决方案:
def num2dict( n, d ): if n < 10: return { n: d } else: q, r = divmod( n, 10 ) return num2dict( q, { r: d } ) print( num2dict( 4388464, { 'words': [ 'getting' ] } ) )
您可以尝试使用递归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)
给出:
我认为递归defaultdict是创建这些长度不可预测的嵌套dict的一种很好的方法。(请注意,如果我们添加的下一个值使用43884作为键,因为d2[4][3][8][8][4]已经存在一个条目,则会出现问题。)
d2[4][3][8][8][4]
import pprint dictionary = { 4388464: ['getting'], 43881: ['got'], 827862 : ['Taruma', 'Varuna'], } d2 = {} def add_it(d, k, words): knum = int(k[0]) if len(k) == 1: d[knum] = {'words': words} else: dsub = d.setdefault(knum, {}) add_it(dsub, k[1:], words) for k, words in dictionary.items(): add_it(d2, list(str(k)), words) pprint.pprint(d2)
印刷品:
制作字典的简短解决方案:
您可以尝试使用递归defaultdict:
给出:
^{pr2}$我认为递归defaultdict是创建这些长度不可预测的嵌套dict的一种很好的方法。(请注意,如果我们添加的下一个值使用43884作为键,因为
d2[4][3][8][8][4]
已经存在一个条目,则会出现问题。)印刷品:
^{pr2}$相关问题 更多 >
编程相关推荐