Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass dict with non string keywords to function in kwargs

I work with library that has function with signature f(*args, **kwargs). I need to pass python dict in kwargs argument, but dict contains not strings in keywords

f(**{1: 2, 3: 4})
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: f() keywords must be strings

How can I get around this without editing the function?

like image 709
atomAltera Avatar asked Feb 20 '13 14:02

atomAltera


People also ask

How do I pass the dictionary to Kwargs?

Passing Dictionary as kwargs “ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.

How do you pass args keyword in Python?

Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.

Why is Kwargs empty?

That dictionary is empty because you have not passed any kwargs in foo1. Note that you should only use variable x and y. Any other variables will cause error.

Are Kwargs dictionaries?

**kwargs is a dictionary of keyword arguments. The ** allows us to pass any number of keyword arguments. A keyword argument is basically a dictionary.


1 Answers

Non-string keyword arguments are simply not allowed, so there is no general solution to this problem. Your specific example can be fixed by converting the keys of your dict to strings:

>>> kwargs = {1: 2, 3: 4}
>>> f(**{str(k): v for k, v in kwargs.items()})
like image 180
Fred Foo Avatar answered Sep 28 '22 03:09

Fred Foo