Python recursive output dictionary all paths of different depths

Source: Internet
Author: User

Application Scenarios

Suppose there is such a dictionary structure test_dict = {' A ': {' B ': {' c ': 1}}, ' d ': 2},test_dict can actually be seen as a tree structure, where each leaf node depth is not necessarily the same, if we want to output the root node to all leaf node paths, That is a->b->c->1;d->2, how to solve?

Code
  
 
  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()
Output Result:
  
 
    1. a
    2. b
    3. c
    4. 1
    5. --------------
    6. d
    7. 2
    8. --------------


From for notes (Wiz)

Python recursive output dictionary all paths of different depths

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.