Python Forum

Full Version: calling a function which takes a dictionary as argument
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I'm having trouble with calling a function which takes a dictionary as argument
for example If I have

dic = {3:0.2, 4:0.5, 5:0.1, 6:0.8, 7:0.34}

def function(**dic):
   if len(dic) == 0:
      return dic
   elif len(dic)>0:
      dic [100] = 0.1
      return dic

function(**dic)
1. basically I first have a dictionary defined, 
2. in the function(which takes this dictionary as argument), if the length of this dictionary is 0, return the original dictionary(an empty dictionary), if the length is larger than zero, add one element to the dictionary, and return the updated version of the dictionary.

so if I want to call this function and get the returned dictionary,
function(**dic)   doesn't work,  what should I do instead? or what I did wrong
You don't need to use the **kwarg syntax to just pass a dict to a function.
**kwarg is used for passing a number of keyword arguments. Any keyword arguments the signature doesn't explicitly handle are put in the kwarg dict doing this.

anyway... this is all you need:
dic = {3:0.2, 4:0.5, 5:0.1, 6:0.8, 7:0.34}
 
def function(dic):
   if not dic:
      return dic
   else:
      dic[100] = 0.1
      return dic
 
function(dic)
print(dic[100])
Oh, ok, thank you so much
Also note, as your function is altering the dictionary in place there is no need for the return statements.

You could just write this:

dic = {3:0.2, 4:0.5, 5:0.1, 6:0.8, 7:0.34}
  
def function(dic):
   if dic:
      dic[100] = 0.1
  
function(dic)
print(dic[100])
Oh, I see,
but I'm actually working on another much more complicated code in which I need to call this function in main, maybe it's safer to do the return...
Anyway, thank you !