简体   繁体   English

字典中的Python函数参数列表

[英]Python function argument list from a dictionary

I'm still relatively new to Python, and sometimes something that should be relatively simple escapes me. 我对Python还是一个相对较新的人,有时候一些本应相对简单的事情却使我无所适从。

I'm storing the results of a POST operation to a database table as a character string formatted as a dictionary definition. 我将POST操作的结果作为格式化为字典定义的字符串存储到数据库表中。 I'm then taking that value and using eval() to convert it to an actual dict object, which is working great as it preserves the data types (dates, datetimes, integers, floats, strings etc.) of the dictionary data elements. 然后,我使用该值,并使用eval()将其转换为实际的dict对象,由于它保留了字典数据元素的数据类型(日期,日期时间,整数,浮点数,字符串等),因此效果很好。

What has me flummoxed is using the resulting dictionary to construct a set of keyword arguments that can then be passed to a function or method. 让我感到困惑的是,使用结果字典构造了一组关键字参数,然后可以将这些参数传递给函数或方法。 So far, I haven't been able to make this work, let alone figure out what the best/most Pythonic way to approach this. 到目前为止,我还无法完成这项工作,更不用说找出最佳/最Pythonic的方式来实现这一目标了。 The dictionary makes it easy to iterate over the dictionary elements and identify key/value pairs but I'm stuck at that point not knowing how to use these pairs as a set of keyword arguments in the function or method call. 字典使遍历字典元素和识别键/值对变得容易,但是在这一点上,我不知道如何在函数或方法调用中将这些对用作一组关键字参数。

Thanks! 谢谢!

I think you're just looking for func(**the_dict) ? 我认为您只是在寻找func(**the_dict)吗?

Understanding kwargs in Python 了解Python中的kwarg

You are looking for **kwargs . 您正在寻找**kwargs It unpacks a dictionary into keyword arguments, just like you want. 就像您想要的那样,它将字典分解成关键字参数。 In the function call, just use this: 在函数调用中,只需使用以下命令:

some_func(**my_dict)

Where my_dict is the dictionary you mentioned. 其中my_dict是您提到的字典。

@tzaman and @Alex_Thornton - thanks - your answers led me to the solution, but your answers weren't clear re the use of the **kwargs in the function call , not the function definition . @tzaman和@Alex_Thornton-谢谢-您的回答使我找到了解决方案,但是您不清楚答案是否是在函数调用中使用**kwargs而不是在函数定义中使用 It took me a while to figure that out. 我花了一段时间才弄清楚。 I had only seen **kwargs used in the function/method definition before, so this usage was new to me. 我以前只在函数/方法定义中看到过**kwargs ,所以这种用法对我来说是新的。 The link that @tzaman included triggered the "aha" moment. @tzaman包含的链接触发了“ aha”时刻。

Here is the code that implements the solution: 这是实现该解决方案的代码:

def do_it(model=None, mfg_date=None, mileage=0):
    # Proceed with whatever you need to do with the 
    # arguments
    print('Model: {} Mfg date: {} Mileage: {}'.format(model, mfg_date, mileage)

dict_string = ("{'model':'Mustang,"
               "'mfg_date':datetime.datetime.date(2012, 11, 24),"
               "'mileage':23824}")

dict_arg = eval(dict_string)

do_it(**dict_arg)  # <---Here is where the **kwargs goes - IN THE CALL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM