Reputation: 189
I'm discovering kwargs and want to use them to add keys and values in a dictionary. I tried this code :
def generateData(elementKey:str, element:dict, **kwargs):
for key, value in kwargs.items():
element[elementKey] = {
"%s": "%s" %(key,value)
}
return element
However, when I use it, I have a TypeError :
*not all arguments converted during string formatting
I tried with
element = generateData('city', element, name = 'Paris', label = 'Paris', postcode = '75000')
and I wanted as result:
element = {'city': {'name': 'Paris', 'label': 'Paris', 'postcode': '75000'}}
Would you know where is my error ?
Upvotes: 2
Views: 1348
Reputation: 1
This also works:
def generate_data(elementKey: str, **kwargs):
y = dict()
y[elementKey] = kwargs
return y
kwargs = {'name' : 'Paris' , 'label' : 'Paris', 'postcode':'75000'}
element = generate_data('city', **kwargs )
print(element)
Upvotes: 0
Reputation: 61910
Just do, since kwargs
is already a dictionary:
def generate_data(elementKey: str, element: dict, **kwargs):
element[elementKey] = kwargs
return element
element = {}
element = generate_data('city', element, name='Paris', label='Paris', postcode='75000')
print(element)
Output
{'city': {'name': 'Paris', 'label': 'Paris', 'postcode': '75000'}}
Upvotes: 4