开发者

Not creating elements when using if / else in python dictionary


Hi,

I'm using if / else conditions to create elements in a dictionnary, such as

x = {
  'id' : id,
  'image' : res['image'] if 'image' in res.keys() else '',
}

Is there a way to not create a image key in the second case ? I cannot remove the else clause, but would like to keep that way of creating the dictionary rather than doing

if 'image' in res.keys():
  x['image'开发者_C百科] = image

Thanks


Python doesn't provide the syntactic sugar to do what you want, but you can slightly change the if statement to fit on one line

if 'image' in res.keys(): x['image'] = image


If you declare a key for a dictioanry, you have to set a value to that so,if you define 'image' you have to set a value for it...

Some other opti,on is:

if 'image' in res.keys():
    x.update({'image':image})

but you can not use anything to define a key-value pair or not while defining the dictionary...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜