Butcher Bnbl
Butcher Bnbl

Reputation: 3

how to store all values of loop in list of dictionary python

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}]

Upvotes: 0

Views: 79

Answers (1)

robinood
robinood

Reputation: 1248

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())

 

Upvotes: 1

Related Questions