Python arguments as a dictionary
83,006
Solution 1
Use a single argument prefixed with **
.
>>> def foo(**args):
... print(args)
...
>>> foo(a=1, b=2)
{'a': 1, 'b': 2}
Solution 2
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
Related videos on Youtube
Author by
Sean W.
Updated on July 09, 2022Comments
-
Sean W. almost 2 years
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.
-
Rob Wouters over 12 yearsPost some code to illustrate, this could mean several things (or perhaps just two).
-
Devin M over 12 yearsSomething like this? stackoverflow.com/a/196997/590177
-
Marcin over 12 yearspossible duplicate of Can you list the keyword arguments a Python function receives?
-
user1066101 over 12 years"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.
-
outis over 12 yearspossible duplicate of Get a list/tuple/dict of the arguments passed to a function?
-
-
jdi over 12 yearsAnd just to add, a single * is used to accept an unnamed amount of non keyword args as a list: *args
-
Makoto over 12 yearsThe result would be:
(1, 2)
{'a': 3, 'b': 4}
. -
Fred Foo over 12 years@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.
-
Vanuan over 11 yearsWhat if I still want the possible keyword arguments (and defaults) to be provided in the function's definition?