rpb
rpb

Reputation: 3299

How to efficiently re-organise dict in Python?

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;

  1. Is the more efficient way compare to the above proposed code. This is because, there are many keys in the secondary level, for the actual case.
  2. Is it possible to have only the combine variable compare to introducing the combine_trim which is used primary for append procedure?

Upvotes: 0

Views: 61

Answers (1)

sushanth
sushanth

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

Related Questions