Python multi-dimensional/nested Dictionary data infinite traversal implementation, python multi-dimensional
Recently I picked up Django and learned how to traverse multi-dimensional Dictionary data in the instance practice. Google does not query related information... After all, I was a newbie. When I started my work, I found that it was not just as simple as I thought. I had two twists and turns to achieve the effect. I recorded the process and hoped it would be useful to everyone.
Instance data (multiple nesting ):
Person = {"male": {"name": "Shawn"}, "female": {"name": "Betty", "age": 23 }, "children": {"name": {"first_name": "Li", "last_name": {"old": "Ming", "now ": "Ming" }}, "age": 4 }}
Purpose:
Traverse all nested Dictionary data in person and display the ideas in key: value mode: first, analyze whether the data conforms to the dictionary feature and print the key of the data and the corresponding value loop to check whether each sub-value of the data conforms to the dictionary feature. If yes, the iteration is executed, if it does not match, the returned loop continues until the execution ends.
Code:
Def is_dict (dict_a): # This method is not used. python has provided the data type detection method isinstance () try: dict_a.keys () Partition t Exception, data: return False return True def list_all_dict (dict_a): if isinstance (dict_a, dict): # Use isinstance to check the data type for x in range (len (dict_a): temp_key = dict_a.keys () [x] temp_value = dict_a [temp_key] print "% s: % s" % (temp_key, temp_value) list_all_dict (temp_value) # implement infinite traversal by self-calling
Result:
Execute list_all_dict (person) and the system responds:
Male: {'name': 'shawn '} name: Shawn children: {'age': 4, 'name': {'first _ name ': '\ xc0 \ xee', 'last _ name': {'right': '\ xc3 \ xfa', 'old ': '\ xc3 \ xf7 \ xc3 \ xf7' }}age: 4 name: {'first _ name': '\ xc0 \ xee', 'last _ name ': {'right': '\ xc3 \ xfa', 'old': '\ xc3 \ xf7 \ xc3 \ xf7'} first_name: Li last_name: {'right ': '\ xc3 \ xfa', 'old': '\ xc3 \ xf7 \ xc3 \ xf7'} now: Ming old: clearly female: {'age': 23, 'name': 'Betty '} age: 23 name: Betty
The implementation of the above multi-dimensional/nested Dictionary data infinite traversal in Python is all the content shared by Alibaba Cloud. I hope you can give us a reference and support for the customer's house.