在Python中,将一个数字串的键拆分为单个数字键
我想翻一下字典:在Python中,将一个数字串的键拆分为单个数字键,python,dictionary,Python,Dictionary,我想翻一下字典: dictionary = { 4388464: ['getting'] 827862 : ['Taruma', 'Varuna'] ... } 进入: 这将允许我使用字典,比如:dictionary[8][2][7][8][6][2][words],而不是:dictionary[827862] 印刷品: {4: {3: {8: {8: {1: {'words': ['got']}, 4: {6: {4: {'words
dictionary = {
4388464: ['getting']
827862 : ['Taruma', 'Varuna']
...
}
进入:
这将允许我使用字典,比如:dictionary[8][2][7][8][6][2][words],而不是:dictionary[827862]
印刷品:
{4: {3: {8: {8: {1: {'words': ['got']},
4: {6: {4: {'words': ['getting']}}}}}}},
8: {2: {7: {8: {6: {2: {'words': ['Taruma', 'Varuna']}}}}}}}
生成词典的简短解决方案:
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)
给出:
- 8:
- 2:
- 7:
- 8:
- 6:
- 2:
- words : ['Taruma', 'Varuna']
- 4:
- 3:
- 8:
- 8:
- 1:
- words : ['got']
- 4:
- 6:
- 4:
- words : ['getting']
我认为递归defaultdict是创建这些长度不可预测的嵌套dict的一种很好的方法。但请注意,如果我们添加的下一个值使用43884作为键,则会出现问题,因为d2[4][3][8][4]已经存在条目.你为什么要这样做?我使用的字典非常大,我很想看看这种方法是否能更快地在字典中找到值。告诉我你在开玩笑。哦,这太尴尬了。打开包含字典的pickle文件需要很长时间!我仍然很好奇如何做到这一点。@THC4k仅在一般情况下,使用一个好的哈希函数。在最坏的情况下,会打开哈希表中的查找。当然,如果在新字典中添加另一个以相同数字开头的条目,则会导致查找失败。是的,我在弄清楚字典的用途之前写了这篇文章。
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']