how to conditionally add a dict in-line

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Tue Feb 24 05:47:23 CET 2009


On Mon, 23 Feb 2009 21:35:38 -0700, Wes James wrote:

> I have this line:
> 
> navs.append(A(' '+str(i+1)+'
> ',_href=self.action(args=request.args,vars=
{'_page':i,'_query':request.vars._query
> or ''})))

What a mess. How can you read it?


> How do I do something like this:
> 
> vars={'_page':i, if request.vars._query not None then insert this
> key/value pair ('_query':request.vars._query) else insert nothing }

vars = {'_page': i}
if request.vars._query is not None:
    vars['_query'] = request.vars._query


See how simple and clear things are when you give up the insistence on 
making everything a one-liner?

But if you *insist* on a one-liner (perhaps because your keyboard has a 
broken Enter key):

vars = {'_page': i} if request.vars._query is None else  {'_page': i, '_query': request.vars._query}




-- 
Steven



More information about the Python-list mailing list