the PHP ternary operator equivalent on Python
Fredrik Lundh
fredrik at pythonware.com
Wed Nov 23 11:27:57 EST 2005
Daniel Crespo wrote:
> Let me tell you something: I'm not a one-liner coder, but sometimes It
> is necesary.
> For example:
> I need to translate data from a DataField to Another.
>
> def Evaluate(condition,truepart,falsepart):
> if condition:
> return truepart
> else:
> return falsepart
>
> dOldDataFields = {}
> dNewDataFields = {}
>
> dNewDataFields = {
> 'CODE': dOldDataFields['CODEDATA'],
> 'DATE': dOldDataFields['DATE'],
> 'CONTACT': Evaluate(dOldDataFields['CONTACTTYPE']==2,
> dOldDataFields['FIRSTCONTACT'], dOldDataFields['SECONDCONTACT'])
> }
>
> With this, I created a new dic very easy, saving in
> dNewDataFields['CONTACT'] the value of dOldDataFields['FIRSTCONTACT']
> or the value of dOldDataFields['SECONDCONTACT'] depending on
> dOldDataFields['CONTACTTYPE']. How you do this in a practic way without
> the use of one-line code? It is needed! You can't avoid it!
if you use less verbose names, you can do the same thing in less than half
the number of characters, without a single oneliner:
def convert(old):
new = dict(
CODE=old['CODEDATA'],
DATE=old['DATE']
)
if old['CONTACTTYPE'] == 2:
new['CONTACT'] = old['FIRSTCONTACT']
else:
new['CONTACT'] = old['SECONDCONTACT']
return new
</F>
More information about the Python-list
mailing list