Replace value in nested list python

How do I replace James's salary from 1000 to 1500 and print James's data?

data = [['Ben', 'Manager', 3000],
           ['James', 'Cleaner', 1000],
           ['Ken', 'Supervisor', 2000]]

for [name,appt,salary] in data:
    if name == 'James':
        salary = 1500
        print[linked_data[1]] 

Here's my current output:

['James', 'Cleaner', 1000]

Expected output:

['James', 'Cleaner', 1500]

Sociopath

12.6k18 gold badges43 silver badges71 bronze badges

asked Jul 13, 2018 at 5:36

1

You need to find the index at which it occurs. Use enumerate.

for idx, [name,appt,salary] in enumerate[data]:
    if name == 'James':
        # salary is at index 2 in the inner list
        data[idx][2] = 1500
        print[f"{name},{appt},{salary}"]

kantal

2,2662 gold badges6 silver badges15 bronze badges

answered Jul 13, 2018 at 5:42

jhuangjhuang

7261 gold badge9 silver badges16 bronze badges

1

You are unpacking from the list in for loop and creating 3 variables name, appt and salary. With this variables it isn't possible to easily change your data structure. What you need is extract a list from data and access it by indexing:

from pprint import pprint

data = [['Ben', 'Manager', 3000],
           ['James', 'Cleaner', 1000],
           ['Ken', 'Supervisor', 2000]]

for d in data:
    if d[0] == 'James':
        d[2] = 1500
        print[d]  # prints only changed row

pprint[data]  # prints whole structure

Prints:

['James', 'Cleaner', 1500]
[['Ben', 'Manager', 3000],
 ['James', 'Cleaner', 1500],
 ['Ken', 'Supervisor', 2000]]

answered Jul 13, 2018 at 5:40

Andrej KeselyAndrej Kesely

133k13 gold badges41 silver badges83 bronze badges

If you know the index then you can do:

data = [['Ben', 'Manager', 3000],
           ['James', 'Cleaner', 1000],
           ['Ken', 'Supervisor', 2000]]


data[1][2] = 1500

print[data[1]]

output:

['James', 'Cleaner', 1500]

answered Jul 13, 2018 at 5:40

SociopathSociopath

12.6k18 gold badges43 silver badges71 bronze badges

You need to access the second sublist of the list and then the third element of the sublist to change it. Have a look at the code below:

data[1][2] = 1500
print[data]

answered Jul 13, 2018 at 5:44

Yash GhorpadeYash Ghorpade

5891 gold badge4 silver badges16 bronze badges

To replace the salary:

data[1][2] = 1500

To print the data:

print[data[1]]

answered Jul 13, 2018 at 5:42

FarhanFarhan

3991 silver badge8 bronze badges

Right now you're trying to iterate over three values that don't actually make sense as parameters to the for loop. What you need to do is access one nested array at a time, check if that array's name is James, and if it is, you change the salary.

data = [['Ben', 'Manager', 3000],
        ['James', 'Cleaner', 1000],
        ['Ken', 'Supervisor', 2000]]

for [person] in data:
    if person[0] == 'James':
        # change index 1 [occupation] to 1500
        person[1] = 1500

print[data]

Output:

[['Ben', 'Manager', 3000],
 ['James', 'Cleaner', 1000],
 ['Ken', 'Supervisor', 2000]]

answered Jul 13, 2018 at 5:43

Ben BotvinickBen Botvinick

2,2291 gold badge15 silver badges36 bronze badges

I would propose using a dictionary to store your information, like this:

data = [['Ben', 'Manager', 3000],
        ['James', 'Cleaner', 1000],
        ['Ken', 'Supervisor', 2000]]

data_dict = {k: {'position': p, 'salary': s} for k, p, s in data}

data_dict['James']['salary'] = 1500

print[data_dict]

Output:

{'Ben': {'position': 'Manager', 'salary': 3000}, 'James': {'position': 'Cleaner', 'salary': 1500}, 'Ken': {'position': 'Supervisor', 'salary': 2000}}

If you need to convert it back to a list, just use this:

print[[[k] + list[v.values[]] for k, v in data_dict.items[]]]

Output:

[['Ben', 'Manager', 3000], ['James', 'Cleaner', 1500], ['Ken', 'Supervisor', 2000]]

answered Jul 13, 2018 at 5:41

Ashish AcharyaAshish Acharya

3,2791 gold badge14 silver badges24 bronze badges

Variable salary is just a copy of the value from data. You should modify the original list instead of the copy. The function enumerate can generate the index [from 0] you need for changing the value inside the list.

data = [['Ben', 'Manager', 3000],
       ['James', 'Cleaner', 1000],
       ['Ken', 'Supervisor', 2000]]

for i, [name, appt, salary] in enumerate[data]:
    if name == 'James':
        data[i][2] = 1500
        print[data[i]]

The output: ['James', 'Cleaner', 1500]

answered Jul 13, 2018 at 5:51

I think using class to replace 2D list is better to do.

class Employee:
    def __init__[self, name, job, salary]:
        self.name = name
        self.job = job
        self.salary = salary

    def __str__[self]:

        return '[{}, {}, {}]'.format[self.name, self.job, self.salary]

    def __repr__[self]:

        return '[{}, {}, {}]'.format[self.name, self.job, self.salary]

data = [Employee['James', 'Cleaner', 1000],
        Employee['Ben', 'Manager', 3000]]

print[data]

for employee in data:
   if employee.name == 'James':
    employee.salary = 1500
    print[employee]
print[data]

Output:

[[James, Cleaner, 1000], [Ben, Manager, 3000]]
[James, Cleaner, 1500]
[[James, Cleaner, 1500], [Ben, Manager, 3000]]

answered Jul 13, 2018 at 5:56

CyrbuzzCyrbuzz

1191 silver badge8 bronze badges

You can also Use This

data = [['Ben', 'Manager', 3000], ['James', 'Cleaner', 1000], ['Ken', 'Supervisor', 2000]]
change = 3000
name = 'Ben'
print[[[x, y, change] if x == name else [x, y, z] for x, y, z in data]]

So You get this Output: [['Ben', 'Manager', 3000], ['James', 'Cleaner', 1000], ['Ken', 'Supervisor', 2000]]

answered Jul 13, 2018 at 6:06

If You Want To Use Simple For Loop Then

data = [['Ben', 'Manager', 3000], ['James', 'Cleaner', 1000], ['Ken', 'Supervisor', 2000]]
for x in data:
    if 'Ben' in x:
        x[-1] = 1500
print[data] 
#Output: [['Ben', 'Manager', 1500], ['James', 'Cleaner', 1000], ['Ken', 'Supervisor', 2000]]

answered Jul 13, 2018 at 6:13

How do I update a nested list in Python?

To add new values to the end of the nested list, use append[] method. When you want to insert an item at a specific position in a nested list, use insert[] method. You can merge one list into another by using extend[] method.

How do you extract an element from a nested list in Python?

Approach #2 : Using zip and unpacking[*] operator This method uses zip with * or unpacking operator which passes all the items inside the 'lst' as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose.

How do you use a nested list in Python?

# creating list..
nestedList = [1, 2, ['a', 1], 3].
# indexing list: the sublist has now been accessed..
subList = nestedList[2].
# access the first element inside the inner list:.
element = nestedList[2][0].

How do I make a nested list one list in Python?

The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in the python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside.

Chủ Đề