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.
2 Answers 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
Comments
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.
1 Comment
ifExplore related questions
See similar questions with these tags.
**kwargssyntax, so maybe read this book.pythontips.com/en/latest/args_and_kwargs.html and loop over the dictionary inside your function?