-1

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...

Eleftheria
  • 143
  • 2
  • 7
  • Is it expected to return a value? – Jonathan Clede Nov 18 '15 at 22:03
  • you need a `return`. – economy Nov 18 '15 at 22:04
  • Are you calling this function, and expecting the reference you used as the argument `my_dict` to contain the copy? If so, it will not. Parameters are passed by the value of the object reference – James Wierzba Nov 18 '15 at 22:06
  • @ Jonathan Clede I need the dictionary that is supposed to be produced by this function – Eleftheria Nov 18 '15 at 22:13
  • @James Wierzba you are right! I am quite new to programming.. I had an idea that as I can pass an empty list inside a function and append it that I could do something similar with a dictionary like pass an empty dictionary and fill it somehow inside a function.. thank you for your theoretical support! – Eleftheria Nov 18 '15 at 22:29

3 Answers3

2
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))
furas
  • 134,197
  • 12
  • 106
  • 148
2

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.

MaxNoe
  • 14,470
  • 3
  • 41
  • 46
  • I need to make it a lot of times for different lists so I thought to try make a fuction to do it for me for all the times needed – Eleftheria Nov 18 '15 at 22:16
0

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)
Eleftheria
  • 143
  • 2
  • 7
James Wierzba
  • 16,176
  • 14
  • 79
  • 120