Home > Mobile >  Updating values inside a python list
Updating values inside a python list

Time:11-21

ItemList = [
    {'name': 'item', 'item_code': '473', 'price': 0},
    {'name': 'item', 'item_code': '510', 'price': 0},
    {'name': 'item', 'item_code': '384', 'price': 0},

]

data_1 = '510'
data_2 = 200

def update_item(data_1, data_2):
    for a in ItemList:
        if a['item_code'] == data_1:
            update_price = append(a['price'].data_2)
            return True

I want to update the price by using the function update_item. It fails at update_price = append(a['price'].data_2)

CodePudding user response:

You can assign the value to the dictionary, with:

def update_item(data_1, data_2):
    for a in ItemList:
        if a['item_code'] == data_1:
            a['price'] = data_2
            return

CodePudding user response:

we can also use the dict update() method to solve this task:

def update_item(data_1, data_2):
    for sub in ItemList:
        if data_1 in sub.values():
            sub.update({'price': data_2})
  • Related