This is two questions, and I'd be happy with either being answered (unless one method is preferred to another).
I have a function, say
def my_func(a, b, c, d = None):
print(a)
print(f"I like {b}")
print(f"I am {c}")
if d:
print(d)
I have a dictionary of keywords my_dict = {'a': 'Hello', 'b': 'Dogs', 'c': 'Happy', 'd': 10} which are always passed as inputs to the function my_func(**kwargs).
My questions are:
I know I can create a new dictionary and pass that in, but I think it would be cleaner if I could do it without needing to do this (though feel free to correct me if I'm wrong!).
Edit: I'm using Python 3.8.
On Python 3.5 and up, you can unpack my_dict
into a new dict and override the 'a'
entry:
my_func(**{**my_dict, 'a': 'Goodbye'})
On Python 3.9 and up, you can use the |
operator to create a new dict by merging entries from two dicts. Values for duplicated keys will be taken from the second dict:
my_func(**my_dict | {'a': 'Goodbye'})