Bart
Bart

Reputation: 59

Change value inside a dictionary with function

I want to change the value of x to 10 by using the table as an argument but it doesn't change value. I also don't want to modify arguments hence copy(). What do I need to do?

def change_x(table):
    new_table = table.copy()
    new_table['x'] = 10

def main():
    table = {
        'x': 8,
        'y': 10
    }
    print(table) # prints 8
    change_x(table) # change value of x to 10
    print(table) # prints 8, wanted 10

Upvotes: 0

Views: 791

Answers (1)

raiyan22
raiyan22

Reputation: 1169

.copy() is a reference to the location where the value is stored and hence it does not change the value. You have to either get rid of the .copy() to change the value or you can return the new dictionary from the change_x function.

def change_x(table):
    table['x'] = 10

def main():
    table = {
        'x': 8,
        'y': 10
    }
    print(table) # prints 8
    change_x(table) # change value of x to 10
    print(table) # prints 10, wanted 10

OR

def change_x_1(table):
        table['x'] = 10
        return table

def main():
        table = {
            'x': 8,
            'y': 10
        }

print(table) # prints 8
print( change_x_1(table) ) # change value of x to 10 and it returns 10, wanted 10

Upvotes: 1

Related Questions