Search code examples
pythonjsonkeyword-argument

Is there a way for me turn json data into positional arguments and their respective values in python?


I am new to python and have been fascinated with **kwargs. So my question is, suppose I have a json of this format:

{
  "arguments" : 
              { 
                "argument1" : "value1",  
                "argument2" : "value2", 
                "argument3": "value3"
              }
 }

How would I be able to pass into a function requires for keyword arguments with the help of **kwarg.

def function1(**kwargs):
    beer=foo.bar(**kwargs)

Where foo.bar only takes in keyword arguments, i.e.

beer=foo.bar(argument1=value1, argument2=value2,....)

Solution

  • my_args = {
        'a': 'hi',
        'b': 'hello',
        'c': 'hey'
    }
    
    
    def my_func(a, b, c):
        print(a, b, c)
    

    Pass my_args in as keyword arguments:

    my_func(**my_args)
    

    Pass my_args in as positional arguments:

    my_func(*my_args.values())