Update the value of sublist where match the key in python?

Viewed 57

Consider the following nested list:

nested_list = [[1, "adam", 20],
               [2, "lucy", 40],
               [3, "mary", 50]]

I would like to do the following conditions for example:
Search '3' keyword, if it is found then check second element is "mary", then update third element.

Pseudo:

if '3' is found in nested_list then
    if index[1] == "mary" then
        index[2] = 50 + 10 (update)
1 Answers

You have a spot on Pseudocode, that we can directly change to code. You have the basic idea, iterate through nested_list check if the first element in any of the lists are equal to 3. Then we need to check the second index and see if that is equal to mary. If both tests pass, we need to update the last element in the list.

code

nested_list = [[1,"adam", 20],[2, "lucy", 40],[3, "mary",50]]
for lists in nested_list:
    if lists[0] == 3 and lists[1] == 'mary':lists[2] += 10

input

[[1,"adam", 20],[2, "lucy", 40],[3, "mary",50]]

output

[[1, 'adam', 20], [2, 'lucy', 40], [3, 'mary', 60]]
Related