douhao6557
2014-09-22 23:47
浏览 211

在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?

图片转代码服务由CSDN问答提供 功能建议

我正在将PHP代码翻译成Python代码,该代码将数据插入到MySql表中。 \ n

基于命名约定有四个可能的列: image_ + [hq,sq,lq,thumb] + _url

php代码如下(使用Laravel DB 查询):

  DB :: table('items')
  - > insertGetId(array(
'title'=> $ title,
'image_  '。$ quality。'_ url'=> $ amazon_url,
)); 
   
 
 

相应的python代码(使用SqlAlchemy Core)给了我一个 语法错误:

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

如何在不恢复if / else语句的情况下在Python中完成相同的结果?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    点赞 评论

相关推荐 更多相似问题