Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How {condition 1: x(), condition 2: y()}.get(True, None) actually run in python?

I recently learned about a way to write if-elif-else. For example:

a = 10
x = {a < 1: 100, a > 1: 200}.get(True, None)

is equal to:

a = 10
if a < 1:
    x = 100
elif a > 1:
    x = 200
else:
    x = None

They will get the same result x = 200

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This new way is more elegant so I use it to replace my following if-elif-else code:

i = 10
j = 0
class A:
    a = 1
class B:
    a = 2
if i:
    x = A()
elif j:
    x = B()
else:
    x = None

to

i = 10
j = 0
class A:
    a = 1
class B:
    a = 2
x = {i: A(), j: B()}.get(True, None)

However, it didn’t run as I wished:

>>> x.a
None

In my opinion, the output of x.a should be 1 because i > 0.

How to explain this?

>Solution :

(Not a direct answer to your question)

I recently learned about a way to write if-elif-else.

Rather than:

a = 10
x = {a < 1: 100, a > 1: 200}.get(True, None)

Prefer this:

a = 10
x = 100 if a < 1 else 200 if a > 1 else None

Which is really more comprehensive, isn’t it?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading