Python Forum
calling a function which takes a dictionary as argument - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: calling a function which takes a dictionary as argument (/thread-1437.html)



calling a function which takes a dictionary as argument - Annie - Jan-03-2017

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


RE: calling a function which takes a dictionary as argument - Mekire - Jan-03-2017

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



RE: calling a function which takes a dictionary as argument - Annie - Jan-03-2017

Oh, ok, thank you so much


RE: calling a function which takes a dictionary as argument - Mekire - Jan-03-2017

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



RE: calling a function which takes a dictionary as argument - Annie - Jan-04-2017

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 !