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 }
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.
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.
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.
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!
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}}
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}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With