Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass same keyword argument to a function twice

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My questions are:

  1. If I want to input a different value, say a=’Goodbye’, is there a way I can input the same argument twice overriding the first entry with the second instance of it?
  2. Alternatively, is there something comparable to my_dict.update({‘a’: ‘Hello’}) that won’t change the values in the dictionary permanently, but will let me pass in a different value for a specific keyword?

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.

>Solution :

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'})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading