24

I would like to my function func(*args, **kwargs) return one dictionary which contains all arguments I gave to it. For example:

func(arg1, arg2, arg3=value3, arg4=value4)

should return one dictionary like this:

{'arg1': value1, 'arg2': value2, 'arg3': value3, 'arg4': value4 }
4
  • looks like the same problem here stackoverflow.com/questions/582056/… Commented Jun 7, 2017 at 12:31
  • 3
    Sounds like an XY problem; since you could simply call dict(arg1=arg1, arg2=arg2, arg3=value3, arg4=value4). What are you actually trying to accomplish? Commented Jun 7, 2017 at 12:36
  • @chepner arg1 = { 'x': 'X', y': 'Y'} arg2 = 2, function func(arg1, arg2, arg3= 3) should return `{'x': 'X', y': 'Y, 'arg2': 2, 'arg3':3} Commented Jun 7, 2017 at 12:54
  • 1
    OK, that's a significantly different outcome than what you are asking about in your question. Commented Jun 7, 2017 at 13:12

3 Answers 3

29

You can use locals() or vars():

def func(arg1, arg2, arg3=3, arg4=4):
    print(locals())

func(1, 2)

# {'arg3': 3, 'arg4': 4, 'arg1': 1, 'arg2': 2}

However if you only use *args you will not be able to differentiate them using locals():

def func(*args, **kwargs):
    print(locals())

func(1, 2, a=3, b=4)

# {'args': (1, 2), 'kwargs': {'a': 3, 'b': 4}}
Sign up to request clarification or add additional context in comments.

4 Comments

Your first output seems strange, arg3&arg4 have values 1&2 instead of 3&4. It should be : {'arg1': 1, 'arg2': 2, 'arg3': 3, 'arg4': 4}
@Nuageux Indeed, was just a copy-paste error. I fixed it.
What if i give dictionary as argument? I will get this { 'args': ({'argX': 'x', 'argY': 'y}, 'arg1': 1) , kwargs': {}} instead o this {'arg1': 1, 'argX': 'x', 'argY': 'y'}
@NikolaMijušković see the "However" part of my answer
5

You are looking for locals()

def foo(arg1, arg2, arg3='foo', arg4=1):
    return locals()

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}

Output:

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}

2 Comments

locals is too broad if there are local variables other than the arguments.
@chepner i presume if you call the as soon as the function is called then it will only list arguments? You could store this as a new variable i think?
3

If you can't use locals like the other answers suggest:

def func(*args, **kwargs):
    all_args = {("arg" + str(idx + 1)): arg for idx,arg in enumerate(args)}
    all_args.update(kwargs)

This will create a dictionary with all arguments in it, with names.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.