douhao6557 2014-09-22 15:47
浏览 427
已采纳

在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-22 16: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部