Hello,
I have the following code that produces a dictionary:
def gen_dict(a, b, c,d,f,**kwargs): data=dict() data.update(Sdate=c) data.update(Edate=d) data.update(freq=f) if kwargs is not None: data.update(kwargs) return data That once given these parameters: a=['JP3705200008'] b=['TR.CompanyMarketCap'] c='03/21/2017' d='03/22/2017' f='D' The outcome is: data={'ShType': 'FFL', 'Frq': 'D', 'Edate': '03/22/2017', 'Curn': 'USD', 'Sdate': '03/21/2017'}
When I try to pass that to get_data(a, b, **data) I get errors, but when I hardcode the dictionary into get_data it works well.
How can I pass dictionaries as arguments to get_data function?
Use get_data(a, b, data) or get_data(a ,b, parameters=data).
When you use "**" notation in front of the variable name you pass to a function, Python unpacks the list or a dictionary inside the variable and provides the elements of the list or the dictionary as arguments for the function. In your example the call get_data(a, b, **data) is equivalent to get_data(a, b, ShType='FFL', Frq='D', Edate='03/22/2017', Curn='USD', Sdate='03/21/2017'), which produces "TypeError: get_data() got an unexpected keyword argument 'ShType'" because get_data method does not have a keyword argument named "ShType". To pass the dictionary as the value for the 3rd position argument of get_data method use get_data(a, b, data). To pass it as the value of the "parameters" keyword argument use get_data(a ,b, parameters=data). Both of these calls are equally valid.