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 ?
CodePudding user response:
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'}}