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

Time:06-18

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

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?

CodePudding user response:

(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?

CodePudding user response:

In python True is equal to 1. They are basically same thing. When you say dict.get(True) you are actually saying dict.get(1). If there is something that is equal to 1, its value will be returned otherwise None will be returned.

In your question:

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

the dict x does not have a key which is equal to 1 so you get None.

Also less code does not always mean it is better. You should prefer writing this code with if statements because it is more readable.

  • Related