52

How can I get argument names and their values passed to a method as a dictionary?

I want to specify the optional and required parameters for a GET request as part of a HTTP API in order to build the URL. I'm not sure of the best way to make this pythonic.

5

2 Answers 2

67

Use a single argument prefixed with **.

>>> def foo(**args):
...     print(args)
...
>>> foo(a=1, b=2)
{'a': 1, 'b': 2}
Sign up to request clarification or add additional context in comments.

3 Comments

And just to add, a single * is used to accept an unnamed amount of non keyword args as a list: *args
@Marcin: Well, maybe I give away code too easily, but this is the kind of construct that I personally always find hard to search for when learning a language.
What if I still want the possible keyword arguments (and defaults) to be provided in the function's definition?
54

For non-keyworded arguments, use a single *, and for keyworded arguments, use a **.

For example:

def test(*args, **kwargs):
    print args
    print kwargs

>>test(1, 2, a=3, b=4)
(1, 2)
{'a': 3, 'b': 4}

Non-keyworded arguments would be unpacked to a tuple and keyworded arguments would be unpacked to a dictionary. Unpacking Argument Lists

1 Comment

The result would be: (1, 2) {'a': 3, 'b': 4}.

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.