Let's say I have some code:
def test(a, b, **kwargs):
print(kwargs)
l = {'a': 0, 'c': 1, 'foo': 2, 'bar': 3}
What I want to do is to pass the unpacked dictionary into the function, but map its key c
to parameter b
, while preserving any other keys that do not directly correspond to a parameter in kwargs, so the function should output {'foo': 2, 'bar': 3}
. If I do test(b=l['c'], **l)
, the key c
remains in kwargs, and output looks like this: {'foo': 2, 'bar': 3, 'c': 1}
. test(**l)
, obviously, crashes with an error - test() missing 1 required positional argument: 'b'
.
How is it possible to do this?
Remove key c
and add b
:
def test(a, b, **kwargs):
print(kwargs)
l = {'a': 0, 'c': 1, 'foo': 2, 'bar': 3}
l2 = l.copy()
l2['b'] = l2['c']
del l2['c']
test(**l2)
Output:
{'foo': 2, 'bar': 3}