[Tutor] Change dictionary value depending on a conditional statement.

Steve Willoughby steve at alchemy.com
Mon Feb 11 20:22:29 CET 2008

Kent Johnson wrote:
> Try
>    list.append({'id': 'name', 'link': ('YY','XX')[total > 0]})

I'd caution against that, though.  It's clever and cute, sure, but the 
meaning of it is obfuscated enough to be unpythonic because [total > 0] 
as a subscript doesn't mean anything unless you know you're taking 
advantage of an implementation detail that booleans are 0 for false and 
1 for true.  No matter how reliable that fact may be, I don't think that 
value should be stuck into a numeric context like that.

> Or, in Python 2.5,
>    list.append({'id': 'name', 'link': ('XX' if total > 0 else 'YY')})

This is much more clear, and would IMHO be fine.

More information about the Tutor mailing list