我有一个字典,其中的关键字是一个字符串,而关键字的值是一组也包含关键字(字链)的字符串。我无法找到图表的最大深度,这是字典中元素最多的集合,我也尝试打印出最大图表。查找字典中的集合的最大深度
现在我的代码打印:
{'DOG': [],
'HIPPOPOTIMUS': [],
'POT': ['SUPERPOT', 'HIPPOPOTIMUS'],
'SUPERPOT': []}
1
其中1是我最大的字典深度。我期待的深度是两个,但似乎只有1层'POT'的图形
如何从字典中的键集中找到最大值集?
import pprint
def dict_depth(d, depth=0):
if not isinstance(d, dict) or not d:
return depth
print max(dict_depth(v, depth+1) for k, v in d.iteritems())
def main():
for keyCheck in wordDict:
for keyCompare in wordDict:
if keyCheck in keyCompare:
if keyCheck != keyCompare:
wordDict[keyCheck].append(keyCompare)
if __name__ == "__main__":
#load the words into a dictionary
wordDict = dict((x.strip(), []) for x in open("testwordlist.txt"))
main()
pprint.pprint (wordDict)
dict_depth(wordDict)
testwordlist.txt:
POT
SUPERPOT
HIPPOPOTIMUS
DOG
http:// stackoverflow。com/questions/9538875 /递归深度的python-dictionary https://www.google.ca/search?q=python+max+depth+of+a+set+in+a+dictionary&ie=utf-8&oe = utf-8&gws_rd = cr&ei = UwscVq6PK8HReo3BsvAI – BAE