Sean W.
Sean W.

Reputation: 5132

Python arguments as a dictionary

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.

Upvotes: 52

Views: 97442

Answers (2)

Bhargav Mangipudi
Bhargav Mangipudi

Reputation: 1233

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

Upvotes: 54

Fred Foo
Fred Foo

Reputation: 363838

Use a single argument prefixed with **.

>>> def foo(**args):
...     print(args)
...
>>> foo(a=1, b=2)
{'a': 1, 'b': 2}

Upvotes: 67

Related Questions