Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert all arguments to dictionary in python

I would like to my function func(*args, **kwargs) return one dictionary which contains all arguments I gave to it. For example:

func(arg1, arg2, arg3=value3, arg4=value4)

should return one dictionary like this:

{'arg1': value1, 'arg2': value2, 'arg3': value3, 'arg4': value4 }
like image 540
nimi Avatar asked Jun 07 '17 12:06

nimi


People also ask

How to convert a dictionary to a list in Python?

Using list () function, we can convert values to a list. 4. Dictionary to List using loop + items () Method Append is a method in python lists that allows you to add an element to the end of the list. By initializing empty elements and then looping through the dictionary.items (), we can append a new list [key, value] in the original list.

How to convert string of valid dictionary to JSON in Python?

This task can easily be performed using the inbuilt function of loads of json library of python which converts the string of valid dictionary into json form, dictionary in Python. The above method can also be used to perform a similar conversion.

How do you iterate through a dictionary in Python?

Iteration is always your friend if you’re unaware of any methods of dictionaries. You can fetch the key by looping through the dictionary and once you have the key, you can use dictionary [key] to fetch its value. Following code uses a similar technique along with .append () function to push elements into a list.

What is a Python dictionary key?

Unlike, numeric indices used by lists, a dictionary uses the key as an index for a specific value. It can be used to store unrelated data types but data that is related as a real-world entity. The keys themselves are employed for using a specific value. Refer to the below article to get the idea about Python Dictionary. Attention geek!


3 Answers

You can use locals() or vars():

def func(arg1, arg2, arg3=3, arg4=4):
    print(locals())

func(1, 2)

# {'arg3': 3, 'arg4': 4, 'arg1': 1, 'arg2': 2}

However if you only use *args you will not be able to differentiate them using locals():

def func(*args, **kwargs):
    print(locals())

func(1, 2, a=3, b=4)

# {'args': (1, 2), 'kwargs': {'a': 3, 'b': 4}}
like image 109
DeepSpace Avatar answered Oct 16 '22 21:10

DeepSpace


You are looking for locals()

def foo(arg1, arg2, arg3='foo', arg4=1):
    return locals()

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}

Output:

{'arg1': 1, 'arg2': 2, 'arg3': 'foo', 'arg4': 1}
like image 45
Arount Avatar answered Oct 16 '22 20:10

Arount


If you can't use locals like the other answers suggest:

def func(*args, **kwargs):
    all_args = {("arg" + str(idx + 1)): arg for idx,arg in enumerate(args)}
    all_args.update(kwargs)

This will create a dictionary with all arguments in it, with names.

like image 25
acdr Avatar answered Oct 16 '22 20:10

acdr