473,799 Members | 3,085 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

the PHP ternary operator equivalent on Python

Hi!

I would like to know how can I do the PHP ternary operator/statement
(... ? ... : ...) in Python...

I want to something like:

a = {'Huge': (quantity>90) ? True : False}

Any suggestions?

Thanks

Daniel

Nov 22 '05
48 2765

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(condit ion,truepart,fa lsepart):
if condition:
return truepart
else:
return falsepart

dOldDataFields = {}
dNewDataFields = {}

dNewDataFields = {
'CODE': dOldDataFields['CODEDATA'],
'DATE': dOldDataFields['DATE'],
'CONTACT': Evaluate(dOldDa taFields['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.

Nov 23 '05 #41
On Wed, 23 Nov 2005 07:01:58 -0800, Daniel Crespo wrote:
WHY WHY WHY the obsession with one-liners? What is wrong with the good old
fashioned way?
if cond:
x = true_value
else:
x = false_value


Let me tell you something: I'm not a one-liner coder, but sometimes It
is necesary.


I'm not arguing for multi-line code just for the sake of using more than
one line. I'm against artificially trying to compress a algorithm that is
naturally expressed in two or more lines into one line.

For example:
I need to translate data from a DataField to Another.

def Evaluate(condit ion,truepart,fa lsepart):
if condition:
return truepart
else:
return falsepart

dOldDataFields = {}
dNewDataFields = {}
Why do you bother to initialise dNewDataFields to an empty dict when you
then populate it in the very next statement?

dNewDataFields = {
'CODE': dOldDataFields['CODEDATA'],
'DATE': dOldDataFields['DATE'],
'CONTACT': Evaluate(dOldDa taFields['CONTACTTYPE']==2,
dOldDataFields['FIRSTCONTACT'], dOldDataFields['SECONDCONTACT'])
}
Doesn't look like a one-liner to me. You've called Evaluate, which takes
five lines by my count.

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! Even using
a = [if_false_expr, if_true_expr][predicate] or a function, you'll
always have to use a one-line code (for this purpose, of course).


Again, I am not arguing for needlessly inflating lines of code, I think
your solution is fine. But just to prove it can be done:

dNewDataFields['CODE'] = dOldDataFields['CODEDATA']
dNewDataFields['DATE'] = dOldDataFields['DATE']
if dOldDataFields['CONTACTTYPE'] == 2:
dNewDataFields['CONTACT'] = dOldDataFields['FIRSTCONTACT']
else:
dNewDataFields['CONTACT'] = dOldDataFields['SECONDCONTACT']
There. The world didn't end.

*wink*

--
Steven.

Nov 23 '05 #42
Steven D'Aprano <st***@REMOVETH IScyber.com.au> writes:
dNewDataFields['CODE'] = dOldDataFields['CODEDATA']
dNewDataFields['DATE'] = dOldDataFields['DATE']
if dOldDataFields['CONTACTTYPE'] == 2:
dNewDataFields['CONTACT'] = dOldDataFields['FIRSTCONTACT']
else:
dNewDataFields['CONTACT'] = dOldDataFields['SECONDCONTACT']

There. The world didn't end.


It gets messy for a more complicated structure:

d = {'x': x1() if x_is_old else x2(),
'y': y1() if y_is_old else y2(),
'z': z1() if z_is_old else z2() }

etc.
Nov 23 '05 #43
Paul Rubin wrote:
It gets messy for a more complicated structure:

d = {'x': x1() if x_is_old else x2(),
'y': y1() if y_is_old else y2(),
'z': z1() if z_is_old else z2() }
etc.


somewhere between the '}' and the '.', a data-driven approach will
be more readable, easier to maintain, and nearly as efficient.

(and with an example as regular as yours, the data table can be auto-
generated...)

</F>

Nov 23 '05 #44
ru***@yahoo.com wrote:
I don't find your code any more readable than the OP's
equivalent code:
the OP's question was

How you do this in a practic way without
the use of one-line code ?
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.


the OPs code contains five reads and three writes, my and
steven's versions contain four reads and three writes. the
yet-to-be-released ternary operator would remove one read
from the OPs code, which makes both alternatives equivalent.

dictionary accesses don't involve passes over the dictionary.

there's a comment on readability and code understanding waiting
to be made here, but I'll leave that for another day.

</F>

Nov 24 '05 #45
ru***@yahoo.com wrote:
Fredrik Lundh wrote:
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 problem I have with your code is that it is too
similar to:

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

Yes, the above code is broken. But it *looks* right, at
first glance, unless you train yourself to never write

if cond: TRUE_CLAUSE
else: FALSE_CLAUSE

as a two-liner.

Regardless of whatever benefits the ternary operator is
going to have, in my opinion allowing people to write
TRUE_CLAUSE if COND else FALSE_CLAUSE will increase the
amount of poorly written, hard to read code.

The OPs code make one pass through the dict, your's makes
two.
The original code binds a name to an empty dict, then
rebinds the name to a populated dict.

Your code simply creates the dict in one step.

Fredrik's code creates an initial dict, then adds a new
key and value to it. That's hardly making two passes
through the dict -- what does that even mean?

I do not know what effect (if any) that has in the case of
a very large dict.

Quick and dirty speed test:

py> from time import time
py> def makedict1():
.... return dict.fromkeys(r ange(1000))
....
py> def makedict2():
.... D = {}
.... for i in range(1000):
.... D[i]=None
.... return D
....
py> assert makedict1() == makedict2()
py> def test(func, n=100):
.... t = time()
.... for i in range(n):
.... tmp = func()
.... return (time() - t)/n
....
py> test(makedict1)
0.0002077984809 8754884
py> test(makedict2)
0.0004240989685 0585936

That's not timing quite the same thing you refer to,
but it is suggestive: if you create an empty dict, and
then populate it one item at a time, it will take
approximately twice as long as creating the non-empty
dict directly.

As a very unscientific, system-dependent, statistically
shoddy ball-park estimate, it looks like each item
assignment to a pre-existing dict takes less than
0.0000002s. So if you had a dict and added another
million items to it, one at a time, it might take an
extra 0.2s in total more than what it would have taken
you if you wrote those one million items in your source
code.

I can live with that.

--
Steven.

Nov 24 '05 #46

Steven D'Aprano wrote:
ru***@yahoo.com wrote:
Fredrik Lundh wrote:
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 problem I have with your code is that it is too
similar to:

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


Huh? How is this similar? Even a glance shows the
indentation is different. It has the same results?
Ok. But why would someone want to assign wrong
values to some of the entries, then go back and fix them?
I think either Fredrick's code or the code I posted is
clearer than this.
Yes, the above code is broken. But it *looks* right, at
first glance,
Yes, I see the error. OLDDCONTACT should be
OLDCONTACT. Are you going to suggest Enum's? :-)
unless you train yourself to never write

if cond: TRUE_CLAUSE
else: FALSE_CLAUSE

as a two-liner.
Oh, that error too... But that error is a compile time
syntax error. Your argument would be much stronger
if it was not a syntax error, but resulted in erroneous
program behavior.
Regardless of whatever benefits the ternary operator is
going to have, in my opinion allowing people to write
TRUE_CLAUSE if COND else FALSE_CLAUSE will increase the
amount of poorly written, hard to read code.


1. Your definitions of hard to read are not the same as mine.
2. Good documentation can mitigate this somewhat.
3. The benefits of being able to write easier to read code
by people with good judgement outweighs the downside.

Nov 24 '05 #47

Fredrik Lundh wrote:
ru***@yahoo.com wrote:
I don't find your code any more readable than the OP's
equivalent code:
the OP's question was

How you do this in a practic way without
the use of one-line code ?


I know. But you compared the readability of code with
one-liners and long variable names with the readability
of code with no one-liners and short variable names.
I thought that most of the readability improvement was
due to the long-to-short name change. So I posted what
I hoped was code equivalent to what you quoted, but
using your short names and a one-liner "then-if-else"
(on 3 lines :-) It satisfied me that the readability
improvement was due to the short varible names.
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.


the OPs code contains five reads and three writes, my and
steven's versions contain four reads and three writes. the
yet-to-be-released ternary operator would remove one read
from the OPs code, which makes both alternatives equivalent.

dictionary accesses don't involve passes over the dictionary.


I was actually thinking of the effects of hardware
memory cache...
there's a comment on readability and code understanding waiting
to be made here, but I'll leave that for another day.


Nov 24 '05 #48
ru***@yahoo.com wrote
dictionary accesses don't involve passes over the dictionary.


I was actually thinking of the effects of hardware
memory cache...


yeah, sure.

</F>

Nov 24 '05 #49

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3836
by: praba kar | last post by:
Dear All, I am new to Python. I want to know how to work with ternary operator in Python. I cannot find any ternary operator in Python. So Kindly clear my doubt regarding this __________________________________ Yahoo! Messenger
0
318
by: Daniel Crespo | last post by:
Hi! I would like to know how can I do the PHP ternary operator/statement (... ? ... : ...) in Python... I want to something like: a = {'Huge': (quantity>90) ? True : False} Any suggestions?
15
12725
by: Arthur Dent | last post by:
Hi all, im just curious if anyone knows..... With .NET 2, VB didnt happen to get a true ternary operator, did it? Stuck away in a corner somewhere? By ternary, i mean something like C's a?b:c syntax. IIf works in most cases, but in some instances you want to use expressions which may fail if they are evaluated when they arent supposed to be, and it would be nice to have a concise way of writing this instead of using a whole If-Then-Else...
5
3569
by: PerlPhi | last post by:
hi,,, while ago i was wondering why do some programmers rarely uses the ternary operator. wherein it is less typing indeed. i believe in the classic virtue of Perl which is laziness. well let me show you something first before i go to my delimma. codes as follows using Mrs. If Else: #!perl/bin/perl use strict; print "Are you sure you want to quit ('yes' or any key for 'no'): "; chomp($_ = <STDIN>);
7
1681
by: kretik | last post by:
I'm sure this is a popular one, but after Googling for a while I couldn't figure out how to pull this off. Let's say I have this initializer on a class: def __init__(self, **params): I'd like to short-circuit the assignment of class field values passed in this dictionary to something like this:
4
2390
by: raiderdav | last post by:
I understand how the ternary operator (question mark - ?) works in an if/else setting, but what does it mean when used as a type? For instance, I'm trying to add a get/set in some existing code, but the return type doesn't match: Rectangle? m_textArea = null; public Rectangle TextArea { set { m_textArea = value; } get { return m_textArea; }
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10484
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10228
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6805
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5585
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4141
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2938
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.