简体   繁体   中英

Is it possible to create a dictionary inside a function using python?

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

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM