Reputation: 143
I am trying the following
def myfunction(list_a, list_b, my_dict):
dict1 = dict(zip(list_a, list_b))
my_dict = copy.deepcopy(dict1)
but when I call myfunction I get an emtpty dictionary...
Upvotes: -1
Views: 9431
Reputation: 17498
Objects are passed by value of the reference, so assigning a new value to the parameter within the function will not change the value of the object reference that was passed to it.
I suggest returning the copy instead.
def myfunction(list_a, list_b):
dict1 = dict(zip(list_a, list_b))
return copy.deepcopy(dict1)
Upvotes: 0
Reputation: 142631
def myfunction(list_a, list_b):
dict1 = dict(zip(list_a, list_b))
return copy.deepcopy(dict1)
my_dict = myfunction(some_list_a, some_list_b)
as MaxNoe noticed - deepcopy is not needed
def myfunction(list_a, list_b):
return dict(zip(list_a, list_b))
my_dict = myfunction(some_list_a, some_list_b)
or even
my_dict = dict(zip(some_list_a, some_list_b))
Upvotes: 2
Reputation: 14987
If you want to make it a function, you should just simply return the dict. No need to give an dictionary or make a deepcopy
:
def dict_from_lists(keys, vals):
return dict(zip(keys, vals))
my_dict = dict_from_lists(list_a, list_b)
But for one line of code only using builtins, I would normally not write a function.
In my opinion
my_dict = dict(zip(list_a, list_b))
is pythonic, it does not need a user function that hides what is going on.
Upvotes: 2