Home > database >  Dealing with nested for Loops in Python to avoid duplicity
Dealing with nested for Loops in Python to avoid duplicity

Time:05-31

In a scenario, we have one data Dictionary which has been traversed as the outer for loop and another data dictionary which will be traversed in the inner for loop.

dict1 = {ABC:India,BND:Argentina}
dict2 = {ABC:Namastey, BND : Hola}

Now, with the help of outer for loop, it will extract the values, India, Argentina etc like :

for key in dict1.keys():
         i_x_0=SubElement(samples, NODE_CONSTANTS['sample_node'])
         val = dict1[key]
         if key =='ABC':
                 append_str = "ASIA_"
                 a1 = append_str val
                 if a1 not in i_x_0:
                     i_x_0.set('intentref', a1)
                     i_x_0.set('count', sample.count)
                     i_x_0.set("excluded", "true")
                     for x in BND.keys():
                          if x not in sample_node:
                           val1 = BND[x]
                           i_x_0.text = val1
         if key =='BND':
                 append_str = "CALA_"
                 a1 = append_str val
                 if a1 not in i_x_0:
                     i_x_0.set('intentref', a1)
                     i_x_0.set('count', sample.count)
                     i_x_0.set("excluded", "true")
                     for x in BND.keys():
                          if x not in sample_node:
                           val1 = BND[x]
                           i_x_0.text = val1                                

If I keep the inner for loop like this, the result will only have Hola and not Namastey in i_x_0 .And if I keep the inner for loop just after the outer loop, it only execute one value per loop which is also not as expected. How can this be modified to get the exact result in i_x_0 , with getting Namastey, Hola etc being set correctly?

CodePudding user response:

There are lots of things you don't explain, but the basic problem is this line:

i_x_0 = SubElement(samples, NODE_CONSTANTS['sample_node'])

It keeps referring to the same SubElement.

I think you need this:

i_x_0 = ET.Element('sample')
samples.append(i_x_0)

This will create a new element every time and you won't keep overwriting stuff.

CodePudding user response:

Below snippet fixed the issue -

temp2 = 1    
        if temp==1:
            temp = temp 1
            print('dict2=',dict2 )
            for key in dict1.keys():
                    if key not in sample_node:
                        i_x_0=SubElement(samples, NODE_CONSTANTS['sample_node'])
                            val = dict1[key]
                            if val not in sample_node:
                              i_x_0.text = dict2[key]
  • Related