Reputation: 3299
The objective is to re-organize the two level dict
in a single level.
Say the two level dict
is given as below:
first_level_one = dict(my='my', ex='ex', second_level=dict(sec_one='sec_one', sec_two='omy'))
first_level_two = dict(my='my', ex='ex', second_level=dict(sec_one='sec_one', sec_two='omy'))
combine = [first_level_one, first_level_two]
The expected output should be:
combine_trim=[dict(my='my', ex='ex', sec_one='sec_one', sec_two='omy'),\
dict(my='my', ex='ex', sec_one='sec_one', sec_two='omy')]
Based on the above requirement, the following code was drafted
first_level_one = dict(my='my', ex='ex', second_level=dict(sec_one='sec_one', sec_two='omy'))
first_level_two = dict(my='my', ex='ex', second_level=dict(sec_one='sec_one', sec_two='omy'))
combine = [first_level_one, first_level_two]
combine_trim=[]
for my_dic in combine:
xx=my_dic['second_level']
my_dic['sec_one']=xx['sec_one']
my_dic['sec_two'] = xx['sec_two']
del my_dic['second_level']
combine_trim.append(my_dic)
There are two question;
combine
variable compare to introducing the combine_trim
which is used primary for append
procedure?Upvotes: 0
Views: 61
Reputation: 8302
try this, use isinstance
to check if value is dict
& using update
add to tmp dict created.
combine_trim=[]
for my_dic in [first_level_one, first_level_two]:
tmp = {}
for k, v in my_dic.items():
if isinstance(v, dict):
tmp.update(v)
else:
tmp[k] = v
combine_trim.append(tmp)
Upvotes: 1