Dictionary, for example:
Dict_all: {
A1: A1,
A2: A2,
B: {B1: B1, B2: B2}
C: {C1: C1,
C2: {CC2: CC2}}
D: {D1: {D2: {D3: ddd3}}
}
When the printing need to display is:
1 A1: A1
A2:2 A2,
3 B:
B1:3.1 B1
B2:3.2 B2
4 C
C1:4.1 C1,
C2:4.2
2 CC2: CC2
5 D
5.1 D1
5.1.1 D2
5.1.1.1 D3: ddd3
With a blank display or recursion depth:
A1: A1
A2: A2,
B:
B1: B1
B2: B2
C:
C1: C1,
C2:
CC2: CC2
D:
D1:
D2:
D3: ddd3
CodePudding user response:
Def dictkey (dictdict) :
For the key in dictdict:
# print (key, dictdict [key])
If the type (dictdict [key])==dict:
Print (key)
Dictkey (dictdict [key])
The else:
Print (key, dictdict [key])
Return
Dict_all={
'A1' : 'A1',
'A2' : 'A2',
'B' : {' B1: 'B1, B2' ':' B2},
'C' : {' C1 ':' C1,
'the C2: {' CC2' : 'CC2'}},
'D' : {' D1: {' D2: {' D3 ':' ddd3 '}}
}}
# print (type (Dict_all), type (Dict_all)==dict)
Dictkey (Dict_all)
CodePudding user response:
Not fully understand, does that mean to write a recursive function, and then decide whether the dictionary, if continue to carry out the recursive function is dictionary, if not the dictionary, the direct outputCodePudding user response:
Def dictkey (dictdict levels) :
For the key in dictdict:
# print (key, dictdict [key])
If the type (dictdict [key])==dict:
Print (" \ t "* levels, key)
Levels +=1
Dictkey (dictdict [key], levels)
The else:
Print (" \ t "* levels, key, dictdict [key])
Return
Dict_all={
'A1' : 'A1',
'A2' : 'A2',
'B' : {' B1: 'B1, B2' ':' B2},
'C' : {' C1 ':' C1,
'the C2: {' CC2' : 'CC2'}},
'D' : {' D1: {' D2: {' D3 ':' ddd3 '}}
}}
# print (type (Dict_all), type (Dict_all)==dict)
Dictkey (Dict_all, 0)
A1 A1
A2 A2
B
B1 B1
B2 B2
C
C1 C1
C2
CC2 CC2
D
D1
D2
D3 ddd3
CodePudding user response:
Def dictkey (dictdict levels) :
For the key in dictdict:
# print (key, dictdict [key])
If the type (dictdict [key])==dict:
Print (" \ t "* levels, key)
Levels +=1
Dictkey (dictdict [key], levels)
Levels -=1
The else:
Print (" \ t "* levels, key, dictdict [key])
Return
Dict_all={
'A1' : 'A1',
'A2' : 'A2',
'B' : {' B1: 'B1, B2' ':' B2},
'C' : {' C1 ':' C1,
'the C2: {' CC2' : 'CC2'}},
'D' : {' D1: {' D2: {' D3 ':' ddd3 '}}
}}
# print (type (Dict_all), type (Dict_all)==dict)
Dictkey (Dict_all, 0)
A1 A1
A2 A2
B
B1 B1
B2 B2
C
C1 C1
C2
CC2 CC2
D
D1
D2
D3 ddd3
CodePudding user response:
Use the upstairs data:Dict_all={
'A1' : 'A1',
'A2' : 'A2',
'B' : {' B1: 'B1, B2' ':' B2},
'C' : {' C1 ':' C1,
'the C2: {' CC2' : 'CC2'}},
'D' : {' D1: {' D2: {' D3 ':' ddd3 '}}
}}
Def printD (d, parDeep, deep) :
For k, v in d.i tems () :
TMP=(' if parDeep==' 'else parDeep) + STR (deep)
If isinstance (v, dict) :
Print (TMP, f "{k} :")
PrintD (v, TMP + ', 1)
The else:
Print (TMP, f '{k}, {n}')
Deep +=1
PrintD (Dict_all, ' ', 1)