Home > database >  how to store all values of loop in list of dictionary python
how to store all values of loop in list of dictionary python

Time:10-21

dic = {}
list =[]

def bathSum():
    for ZPRODHDR in root.iter('ZPRODHDR'):
        for ZPRODITM in ZPRODHDR.iter('ZPRODITM'):
            component = ZPRODITM.findtext('COMPONENT')
            quantity =  ZPRODITM.findtext('QUANTITY')
            component = int(component)
            quantity =  float(quantity)
            dic[component] = quantity 
        list.append(dic) 
        print('dictionary print', dic)  
    return(list)
    
print('list of dictionaries', bathSum())  

How I can get output list of dictionaries like in 'dictionary print'?Because it seams to overwrite all values in each dictionary for last loop values.

dictionary print: {60943240: 814.0, 60943245: 557.0} dictionary print: {60943240: 793.0, 60943245: 482.0}

list of dictionaries: [{60943240: 793.0, 60943245: 482.0}, {60943240: 793.0, 60943245: 482.0}]

CodePudding user response:

The problem is that you are not resetting your dictionary dic at each ZPRODHDR loop. The values are then always updated in the original dictionnary, and always overriding the old values. This variable is an intermediate variable that should be cleaned at each loop from its values. You need to move the dic variable declaration inside your first for loop.

list =[]

def bathSum():
    for ZPRODHDR in root.iter('ZPRODHDR'):
        dic = {}
        for ZPRODITM in ZPRODHDR.iter('ZPRODITM'):
            component = ZPRODITM.findtext('COMPONENT')
            quantity =  ZPRODITM.findtext('QUANTITY')
            component = int(component)
            quantity =  float(quantity)
            dic[component] = quantity 
        list.append(dic) 
        print('dictionary print', dic)  
    return(list)
    
print('list of dictionaries', bathSum())

 
  • Related