51

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.

bool.dev
  • 17,508
  • 5
  • 69
  • 93
Sean W.
  • 4,944
  • 8
  • 40
  • 66
  • 6
    Post some code to illustrate, this could mean several things (or perhaps just two). – Rob Wouters Jan 21 '12 at 16:50
  • Something like this? http://stackoverflow.com/a/196997/590177 – Devin M Jan 21 '12 at 16:51
  • possible duplicate of [Can you list the keyword arguments a Python function receives?](http://stackoverflow.com/questions/196960/can-you-list-the-keyword-arguments-a-python-function-receives) – Marcin Jan 21 '12 at 17:06
  • "I’m wanting to wanting to specify the optional and required parameters for a GET request"? Can you expand on this? It makes very little sense. – S.Lott Jan 21 '12 at 17:41
  • possible duplicate of [Get a list/tuple/dict of the arguments passed to a function?](http://stackoverflow.com/questions/2521901/get-a-list-tuple-dict-of-the-arguments-passed-to-a-function) – outis Jan 21 '12 at 18:45

2 Answers2

66

Use a single argument prefixed with **.

>>> def foo(**args):
...     print(args)
...
>>> foo(a=1, b=2)
{'a': 1, 'b': 2}
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 5
    And just to add, a single * is used to accept an unnamed amount of non keyword args as a list: *args – jdi Jan 21 '12 at 17:01
  • 13
    @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. – Fred Foo Jan 21 '12 at 19:01
  • 2
    What if I still want the possible keyword arguments (and defaults) to be provided in the function's definition? – Vanuan Jan 23 '13 at 14:27
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

Michael Dillon
  • 1,037
  • 6
  • 16
Bhargav Mangipudi
  • 1,215
  • 2
  • 10
  • 13