the PHP ternary operator equivalent on Python

rurpy at yahoo.com rurpy at yahoo.com
Wed Nov 23 14:57:05 EST 2005


Fredrik Lundh wrote:
> 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

I don't find your code any more readable than the OP's
equivalent code:

def convert(old):
    new = {
	CODE: old['CODEDATA'],
	DATE: old['DATE'],
	CONTACT: old['FIRSTCONTACT'] \
	    if old['CONTACTTYPE'] == 2 \
	    else old['OLDDCONTACT']
	}
    return new

The OPs code make one pass through the dict, your's makes
two.  I do not know what effect (if any) that has in the case of
a very large dict.




More information about the Python-list mailing list