Recently picked up Django Learning, example practice encountered in the multidimensional dictionary type data traversal operation problem, Google query no relevant information ... After all, the novice, to their own hands when found not simple to imagine, quite two twists and turns to achieve the final effect, the process of recording down hope for everyone useful.
Instance data (multiple nesting):
person = {"Male": {"name": "Shawn"}, "female": {"name": "Betty", "Age": "}", "Children": {"name": {"first_name": "Li", "Last_" Name ": {" old ":" Ming "," Now ":" Ming "}}," Age ": 4}}
Objective:
Iterate through all nested dictionary type data in person and display ideas in a key:value way: first, analyze whether the data conforms to the dictionary characteristics print the key of the data and corresponding value loop to check that each child value of the data conforms to the dictionary feature, and if it is compliant, the iteration executes, Does not conform returns the loop continues execution to the end
Specific code:
def is_dict (dict_a): #此方法弃用, Python has provided data type detection methods isinstance ()
try:
Dict_a.keys ()
except Exception, data: Return
False return
True
def list_all_dict (dict_a):
if Isinstance (dict_a,dict): # Use Isinstance to detect 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) #自我调用实现无限遍历
Results:
Execute list_all_dict (person), System response:
Male: {' name ': ' Shawn '}
name:shawn
children: {' age ': 4, ' name ': {' first_name ': ' \xc0\xee ', ' last_name ': {' Now ' : ' \xc3\xfa ', ' old ': ' \xc3\xf7\xc3\xf7 '}}
age:4
name: {' first_name ': ' \xc0\xee ', ' last_name ': {' Now ': ' \xc3\ Xfa ', ' old ': ' \xc3\xf7\xc3\xf7 '}
first_name: Li
last_name: {' Now ': ' \xc3\xfa ', ' old ': ' \xc3\xf7\xc3\xf7 '} Now
: Ming old
: clearly
female: {' age ': ", ' name ': ' Betty '}
age:23
name:betty
This python multidimensional/nested dictionary data Unlimited traversal of the implementation of the small set to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.