Updating values inside a python list

Question:

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)

Asked By: ETHERC20

||

Answers:

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
Answered By: Willem Van Onsem

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})
Answered By: lroth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.