Racana
Racana

Reputation: 327

Python Appending Dictionaries within function

I'm trying to understand how functions work, I created a function that takes 2 dictionaries as arguments and returns 1 single dictionary. When I run the function it works as expected and returns the full dictionary. The purpose of the function is to iterate over a for loop and drop the data in y

def testing_dict(x, y):
    y = {**x, **y}
    return y

x = {"a": 1, "b": 2, "c": 3}
y = {}

testing_dict(x, y)

Out: {'a': 1, 'b': 2, 'c': 3}

but if I run y I get an empty dictionary, when I want is to store all the values from x

y
Out: {} 

Upvotes: 0

Views: 58

Answers (1)

Mike67
Mike67

Reputation: 11342

(Moving comment to answer)

In your function, you are setting a local variable y which is not the same as the global y defined outside the function.

To access the local value, there are two options:

► Use the return value of the function to set the global variable:

y = testing_dict(x,y)  # get return value

► Update the global variable from the function:

def testing_dict(x, y):
    global y  # access global variable
    y = {**x, **y}  # set global variable
    return y   

Upvotes: 1

Related Questions