Search code examples
pythonclassdictionaryif-statementget

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

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?