douhao6557 2014-09-22 23:47
浏览 426
已采纳

在Python中使用变量修改参数名称

I'm translating PHP code to Python code which inserts data into a MySql table.

There are four possible columns based on a naming convention: image_ + [hq,sq, lq, thumb] + _url

The php code is as follows (using Laravel DB Query):

DB::table('items')
                ->insertGetId(array(
                   'title' => $title,
                    'image_' . $quality . '_url' => $amazon_url,
                ));

The corresponding python code (using SqlAlchemy Core) which is giving me a syntax error:

item_ins = items_tbl.insert().values(title=item_title, 
                                                   image_+quality+_url=amazon_url

            )

How can I accomplish the same result in Python without reverting to if/else statements?

  • 写回答

1条回答 默认 最新

  • duanlie7962 2014-09-23 00:00
    关注

    You can't have variably named keyword arguments in a Python function call. However, you can expand a dict into keyword arguments:

    item_ins = items_tbl.insert().values(**{'title' : item_title,
                                            'image_'+quality+'_url' : amazon_url})
    

    If quality=='hq' for example, this is equivalent to calling

    item_ins = items_tbl.insert().values(title = item_title,
                                         image_hq_url: amazon_url)
    

    You should also note that in the syntax you tried to use, you tried to treat image_ and _url as string literals and quality as a variable, without making any syntactic distinction between them. There's no way that would work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?