I have a function with some named parameters, and a dictionary that contains keys with those names, as well as some other keys. I want to call the function with values from the dictionary.
- I can't use
**data
because Python will raiseTypeError: unexpected keyword argument
because of the extra keys. - The dict might not contain certain keys, so I can't reference the keys without checking that they exist (and I don't want to pass a default from
get
). - I can't rewrite the function because it is in a separate library.
How can I unpack only the keys that match the function parameters?
def do_something(arg1=None, arg2=''):
...
data = {'arg1': 1, 'arg2': 2, 'other': 3}
# doesn't work if key doesn't exist
do_something(arg1=data['arg1'], arg2=data['arg2'])
# too verbose, hard to extend
if 'arg1' in data:
do_something(arg1=data['arg1'], arg2=data['arg2'])
else:
do_something(arg2=data['arg2'])