应用场景

假设有这样一个字典结构test_dict = {'a':{'b':{'c':1}},'d':2},test_dict其实可以看作是一种树状结构,其中每个叶子节点深度不一定相同,如果我们希望输出根节点到所有叶子节点的路径,也就是a->b->c->1;d->2,该如何解决?

代码

  1. #encoding=utf-8
  2. import sys
  3. def recurPrintPath(dic):
  4. for key in dic.keys():
  5. print key
  6. #判断下一级是否还是字典,如果是字典继续递归
  7. if type(dic[key]) == type({}):
  8. recurPrintPath(dic[key])
  9. else:
  10. print dic[key]
  11. print '--------------'
  12. def main():
  13. reload(sys)
  14. sys.setdefaultencoding('utf-8')
  15. test_dict = {'a':{'b':{'c':1}},'d':2}
  16. recurPrintPath(test_dict)
  17. if __name__ == '__main__':
  18. main()

输出结果:

  1. a
  2. b
  3. c
  4. 1
  5. --------------
  6. d
  7. 2
  8. --------------




相关文章:

  • 2022-12-23
  • 2021-12-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-24
猜你喜欢
  • 2021-06-17
  • 2022-12-23
  • 2022-01-20
  • 2022-12-23
  • 2021-09-06
  • 2022-12-23
  • 2021-06-06
相关资源
相似解决方案