Search code examples
pythonlistinsert-update

Update items in a list based on another list


I have a list which contains names, position and points, then there is an new list which I manage to get the data's from a game api, loops it and appends it after that it will empty the newlist and rinse repeat (in my example I won't put the api loop code instead I will put the kind of data I get to make it simple)

list = [
        ['Charlie', '3', '2000'],
        ['Bill', '2', '2100'],
        ['Alan', '1', '2200']
        ]

newlist = [
        ['Charlie', '3', '2300'],
        ['Bill', '2', '2350'],
        ['Alan', '1', '2400']
        ]

#doesn't work as mentioned previously  
list.append(updatedlist)

print(list)

So all I need is to update the new list to the main list, as you can see, for a given name-position pair, the score changes in the new list.

I want the original list to reflect the updated scores. How can I do this?


Solution

  • One fundamental assumption is that, in your use case, lst (don't use list to name your objects) is certainly much bigger than newlist, and not all entries are subject to update (or else you could've just done lst = newlist).

    Another assumption here is that the first two elements in a tuple form the "key", and the last element forms the "value" for each entry. We'll use this setup for our solution.

    A brute force solution would involve a nested loop and run in quadratic time. You can hash your data and reduce this to a linear operation, using an OrderedDict to maintain order.

    Let the dictionary handle the update for you.

    from collections import OrderedDict
    
    # initialise an ordered dictionary from your existing data
    o = OrderedDict((v[:-1], v[-1]) for v in lst)
    # initialise an ordered dictionary from your new data
    o_new = OrderedDict((v[:-1], v[-1]) for v in newlist)
    # update current entries with new/updated entries 
    o.update(o_new)
    
    lst_updated = [k + (v, ) for k, v in o.items()]
    

    print(lst_updated)
    [('Charlie', '3', '2300'), ('Bill', '2', '2350'), ('Alan', '1', '2400')]