Home > Software engineering >  Repeating values when we use append function in list or update in dict
Repeating values when we use append function in list or update in dict

Time:01-20

when I try to append a Dictonary values to a list I'm getting the value appended multiple time but when I try to see what is really happening in there by using print statement, the values are iterating properly but while appending it is appending same value multiple times

Here is my code

from random import randint
x = {'1': 
        {
            'item_id': 6,
            'item_name': 'burger',
            'item_price': 10,
            'item_quantity': 2
        }, 
    '2': 
        {
            'item_id': 7,
            'item_name': 'pizza',
            'item_price': 15,
            'item_quantity': 4
        },
     '3':
        {
            'item_id': 8,
            'item_name': 'Biryani',
            'item_price': 20,
            'item_quantity': 6
            
        }
    }
cart=[]
items = {}
for y in x.values():
    items['name'] = y['item_name']
    items['price'] = y['item_price']
    items['quantity'] = y['item_quantity']
    print(items)
    cart.append(items)
print(cart)

And This is the Output:

{'name': 'burger', 'price': 10, 'quantity': 2}
{'name': 'pizza', 'price': 15, 'quantity': 4}
{'name': 'Biryani', 'price': 20, 'quantity': 6}
[{'name': 'Biryani', 'price': 20, 'quantity': 6}, {'name': 'Biryani', 'price': 20, 'quantity': 6}, {'name': 'Biryani', 'price': 20, 'quantity': 6}]
> 

CodePudding user response:

You are mutating and appending the same dict items to cart again and again. Instantiate a new dict items = {} in each iteration of the for loop.

CodePudding user response:

try initializing your dictionary every time inside the loop

cart=[]
for y in x.values():
    items = {}
    items['name'] = y['item_name']
    items['price'] = y['item_price']
    items['quantity'] = y['item_quantity']
    print(items)
    cart.append(items)
print(cart)
  •  Tags:  
  • Related