Home > database >  Python : List duplicates values when appending
Python : List duplicates values when appending

Time:10-06

I have a code with two line items

lineitem: {'line_code': 'UU', 'product_name': 'Apple', 'product_number': 'A090','quantity': '8', 'current_cost': '198.76'} {'line_code': 'UU', 'product_name': 'Orange', 'product_number': 'O8U8', 'quantity': '1','current_cost': '118.64'}

I want to create a list with some of the data in LineCode Below is my code:

                    LineCode =  res['response']['data']['GetFruitList']

                    ValuesinList = []
                    dictionary = {}
                    keys = ['ShippingAddress', 'ProductNumber', 'Quantity', 'Price', 'LineCode', 'Count']

                    for lineitem in LineCode:
                        LineCode = lineitem.get('line_code')
                        ProductNumber = lineitem.get('product_number')
                        Quantity = lineitem.get('quantity')
                        
                        values = [ShippingAddress, ProductNumber, Quantity, Price, LineCode, 'Many']
                        for key, value in zip(keys, values):
                            dictionary[key] = value
                        print("print" str(dictionary))
                    ValuesinList.append(dictionary)
                    print(ValuesinList)

So here i parse through LineCode , and appends the needed information like LineCode,ProductNumber,Quantity,Price into a dictionary which is later appended to a list. but current when i run the code it gives ValueinList as :

[{'line_code': 'UU', 'product_name': 'Orange', 'product_number': 'O8U8', 'quantity': '1'},{'line_code': 'UU', 'product_name': 'Orange', 'product_number': 'O8U8', 'quantity': '1'}]

which is it appends the last value twice . what i want is,

[{'line_code': 'UU', 'product_name': 'Apple', 'product_number': 'A090','quantity': '8'},{'line_code': 'UU', 'product_name': 'Orange', 'product_number': 'O8U8', 'quantity': '1'}]

Can anyone please help

CodePudding user response:

Try this:

ValuesinList = []
LineCode = [{'line_code': 'UU', 'product_name': 'Orange', 
         'product_number': 'O8U8', 'quantity': '1',
         'current_cost': '118.64'},
        {'line_code': 'UU', 'product_name': 'Orange', 
         'product_number': 'O8U8', 'quantity': '1',
         'current_cost': '118.64'}]

for lineitem in LineCode: 
    dicct = {}
    dicct['ShippingAddress'] = lineitem.get('line_code')
    dicct['ProductNumber'] = lineitem.get('product_number')
    dicct['Quantity'] = lineitem.get('quantity')
    dicct['Price'] = lineitem.get('current_cost')
    print("Price inside the List sending " str(dicct['Price']))
    print("print" str(dicct))
    ValuesinList.append(dicct)

print(ValuesinList)

Hope it helps

  • Related