Jack022
Jack022

Reputation: 1257

Updating a list of lists in Python

I have the following list of lists:

MyList = [[130, 10], [131, 15], [132, 1]]

Then i have some inputs. If i get, for example: Data = [130, 3], [135, 10], i need to update the list like this:

MyList = [[130, 3], [131, 15], [132, 1], [135, 10]]

So, if in MyList there is already a sublist where the first element is the same as the first element of a sublist in Data, update the same element. Instead, if there isn't one, append it.

I managed to do this but i was wondering if there was a cleaner solution, as i really don't like the actual one:

Temp = [x[0] for x in MyList]

for x in Data:
    if x[0] not in Temp:
        Sublist = []
        Sublist.append(x[0])
        Sublist.append(x[1])
        MyList.append(Sublist)
    else:
        for y in MyList:
            if x[0] == y[0]:
                x[1] = y[1]

Is there any better way to do this? I feel like this code can be improved, i also don't like editing elements while looping. Any kind of help is welcome!

Upvotes: 1

Views: 2513

Answers (4)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95873

The cleanest solution would be to use a dict to begin with. So,

>>> data = dict([[130, 10], [131, 15], [132, 1]])
>>> data
{130: 10, 131: 15, 132: 1}
>>> for x, y in [130, 3], [135, 10]:
...     data[x] = y
...
>>> data
{130: 3, 131: 15, 132: 1, 135: 10}

If you really need a list at the end:

>>> list(data.items())
[(130, 3), (131, 15), (132, 1), (135, 10)]

Or even just:

>>> data = {130: 10, 131: 15, 132: 1}
>>> new_data = [130, 3], [135, 10]
>>> data.update(new_data)
>>> data
{130: 3, 131: 15, 132: 1, 135: 10}

Upvotes: 4

sahasrara62
sahasrara62

Reputation: 11228

As per your this question, what you can do is extend your main list with all the data, and then use dict operation to make a dictionary

MyList = [[130, 10], [131, 15], [132, 1]]


new_data = [[130, 3], [135, 10]]

MyList.extend(new_data)

final_data=  dict(MyList)
print(final_data)
# {130: 3, 131: 15, 132: 1, 135: 10}

Upvotes: 0

Hamza
Hamza

Reputation: 6025

A cleaner solution (if you insist to use lists instead of the preferred structure dictionary) might be:

MyList = [item for item in MyList if item[0] not in [i[0] for i in Data]]
MyList.extend(Data)

Upvotes: 0

Toma Margishvili
Toma Margishvili

Reputation: 29

If I got your problem right, this is what I have in mind, similar to yours.

myList = [[130, 10], [131, 15], [132, 1]]
data = [130, 3], [135, 10]

if data[0][0] == myList[0][0]:
    myList.pop(0)
    myList.insert(0, data[0])
    myList = myList + list(data[1:])
else:
    myList = myList + list(data)

print(myList)

output:

[[130, 3], [131, 15], [132, 1], [135, 10]]

Upvotes: 0

Related Questions