The implementation of Python multidimensional and for the infinite traversal of nested dictionary data
- 2020-05-17 05:46:20
- OfStack
Recently, I encountered the problem of ergodic operation on multidimensional dictionary type data in the sample exercise. There is no relevant information in the Google query. After all, I am a novice. When I start my own work, I find it is not as simple as I imagined. There are quite two twists and turns before I finally achieve the effect.
Instance data (multiple nesting) :
person = {"male":{"name":"Shawn"}, "female":{"name":"Betty","age":23},"children":{"name":{"first_name":" li ", "last_name":{"old":" Ming Ming ","now":" Ming "}},"age":4}}
Objective:
Traverse all nested dictionary type data in person, and display them in the form of key: value: first, analyze whether the data conforms to dictionary features; print key of the data and the corresponding value loop to check whether each child value of the data conforms to dictionary features; if it does, iterate; if not, return to the loop and continue to execute until the end
Specific code:
def is_dict(dict_a): # This method is deprecated, python A data type detection method is provided 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 Detection 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) # Self - invocation to achieve infinite traversal
Results:
Execute list_all_dict(person), the system responds:
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 : Ming Ming
female : {'age': 23, 'name': 'Betty'}
age : 23
name : Betty