1

I have a nested dictionary. I do not know it's structure ahead. I would like to create a non-nested dictionary from this.

I created a recursive function to do this task but I am wondering if there is a faster way to achieve this.

My recursive function looks like as follows:

Suppose I have a nested dictionary such as:

  dic = {"A1":{"B1":{"C":3},
              "B2":{"D1":"a",
                    "D2":"nested within D2",
                    "D3":{"E1":1,"E2":2}}},
         "A2":100}

Then my recursive function is:

   def recurse(dic,prefix="",myrow={}):
      ## dic: dictionary
      for key in dic.keys():

        dickey = dic[key]
        if isinstance(dickey,dict):
            recurse(dickey,prefix + key + "_" ,myrow)
        else:
            myrow[ prefix + key ] = dickey

      return myrow

This will give the non-nested dictionary: recurse(dic)

{'A1_B1_C': 3,
 'A1_B2_D1': 'a',
 'A1_B2_D2': 'nested within D2',
 'A1_B2_D3_E1': 1,
 'A1_B2_D3_E2': 2,
 'A2': 100}
FairyOnIce
  • 2,526
  • 7
  • 27
  • 48

0 Answers0