my_dict1 = {'a':1, 'chk':{'b':2, 'c':3}, 'e':{'chk':{'f':5, 'g':6}} }
I would like to loop through the dict recursively and if the key is 'chk', split it.
Expected output:
{'a':1, 'b':2, 'e':{'f':5}}
{'a':1, 'c':3, 'e':{'f':5}}
{'a':1, 'b':2, 'e':{'g':6}}
{'a':1, 'c':3, 'e':{'g':6}}
Not sure of how to achieve this. Please help.
What I have tried is below.
temp_list =[]
for k,v in my_dict1.iteritems():
temp ={}
if k is "chk":
for key,val in v.iteritems():
temp[key] = val
my_dict1[k]={}
for ky,vl in temp.iteritems():
my_new_dict = copy.deepcopy(my_dict1)
for k,v in my_new_dict.iteritems():
if k is "chk":
my_new_dict[k] = {ky:vl}
temp_list.append(my_new_dict)
print temp_list
output:
[{'a': 1, 'chk': ('c', 3), 'e': {'chk': {'f': 5, 'g': 6}}},
{'a': 1, 'chk': ('b', 2), 'e': {'chk': {'f': 5, 'g': 6}}}]
How to make it recursive?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…