Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 482
Sean W. Avatar asked Jan 21 '12 16:01

Sean W.


People also ask

How do you add an argument to a dictionary in Python?

For non-keyworded arguments, use a single * , and for keyworded arguments, use a ** . The result would be: (1, 2) {'a': 3, 'b': 4} .

How does Python pass dictionary as Kwargs?

Use the Python **kwargs parameter to allow the function to accept a variable number of keyword arguments. Inside the function, the kwargs argument is a dictionary that contains all keyword arguments as its name-value pairs. Precede double stars ( ** ) to a dictionary argument to pass it to **kwargs parameter.

What are the 3 types of arguments in Python?

Hence, we conclude that Python Function Arguments and its three types of arguments to functions. These are- default, keyword, and arbitrary arguments.

How do you pass a value to a dictionary in Python?

To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {} and separate them using a comma ( , ). Each entry consists of a key and a value, also known as a key-value pair. Note: The values can belong to any data type and they can repeat, but the keys must remain unique.


1 Answers

Use a single argument prefixed with **.

>>> def foo(**args): ...     print(args) ... >>> foo(a=1, b=2) {'a': 1, 'b': 2} 
like image 93
Fred Foo Avatar answered Sep 20 '22 22:09

Fred Foo