0

I want to write a code that will check a dictionary for a key and if exist to set it to a function as a parameter.

def myFunction(*args, **kwargs):
 # do stuffs
 if('name' in kwargs):
 thisTitle = kwargs.pop('name') 
 print(thisTitle)
 ...
 return thisTitle
t = {}
if 'name' in t.keys() 
 and 'param1' in t.keys() 
 and 'param2' in t.keys():
 res = myFunction(name = t['name'], 
 myparam1 = t['param1'],
 secondPar = t['param2'])
elif 'name' in t.keys() 
 and 'param1' in t.keys():
 res = myFunction(name=t['name'], 
 myparam1=t[param1])
elif 'name' in t.keys():
 res = myFunction(name=t['name'])

What if I had 10 parameters? There must be a better way.

asked Dec 11, 2018 at 12:17
1

2 Answers 2

2

Try this:

def myFunction(*args, **kwargs):
 # do stuffs
 if('name' in kwargs):
 thisTitle = kwargs.pop('name')
 print(thisTitle)
 if('param1' in kwargs):
 print(kwargs['param1'])
 if('param2' in kwargs):
 print(kwargs['param2'])
 # ...
 return thisTitle
t = {'name': "same_name"}
myFunction(**t)
t = {'name': 'same_name',
 'param1': 'val1',
 'param2': 'val2'}
myFunction(**t)

Output:

$ python3 stack.py 
same_name
same_name
val1
val2
answered Dec 11, 2018 at 12:26
Sign up to request clarification or add additional context in comments.

Comments

0

I would also suggest using the default argument on pop rather than checking for existence: thisTitle = kwargs.pop('name', default); so you don't do both a in and a pop.

if('name' in kwargs):
 thisTitle = kwargs.pop('name')

Becomes:

thisTitle = kwargs.pop('name', None)

It might be better to use get rather than pop unless removing the key from the dictionary is an required effect:

thisTitle = kwargs.get('name', None)

Your function then would return None rather than producing a NameError when the name keyword argument is not provided.

answered Dec 11, 2018 at 13:03

1 Comment

Thanks @Dan D, very useful tip !! I was setting a default value always just before if

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.