Python – Update the items in the list based on another list

Update the items in the list based on another list… here is a solution to the problem.

Update the items in the list based on another list

I have a list with names, locations, and points, then there’s a new list, I manage to get the data from the game api, loop it and

append it, after which it will empty the new list and flush the duplicates (in my example I don’t put the api loop code, but 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 I just need to update the new list to the main list, and as you can see, the score in the new list changes for a given name-position pair.

I want the original list to reflect the updated score. What should I do?

Solution

A basic assumption is that in your use case, lst (don’t use list to name your objects) is definitely much larger than newlist<, and not all entries need to be updated (otherwise you can do lst = newlist directly).

Another assumption here is that the first two elements in the tuple form the “key” and the last element constitutes the “value” of each entry. We will use this setting to solve our problem.

A brute force solution will involve nesting loops and running in quadratic time. You can hash the data and simplify it to linear operations, using OrderedDict to maintain order.

Let the dictionary handle the updates 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')]

Related Problems and Solutions