NG_21
NG_21

Reputation: 725

How to correctly write boolean expression involving python dictionaries

I have two python dictionary structures in which I am looking up for a specific key. But python evaluates it to None if the value is 0 . I am using Python2.7

A = {'distribution_1':{'mu':0.0,'sigma':0.5}}
B = {'distribution_1':{'sigma':0.1}}
x = A.get('mu') or B.get('mu') # This evaluates to None, expected 0.0

whereas

A = {'distribution_1':{'mu':0.1,'sigma':0.5}}
B = {'distribution_1':{'sigma':0.1}}
x = A.get('mu') or B.get('mu') # This evaluates to 0.1

To set the context, these two dictionaries contain parameters for probability distributions

Upvotes: 0

Views: 640

Answers (1)

Ala Tarighati
Ala Tarighati

Reputation: 3817

In the first case, it is better using A["distribution_1"].get('mu') while this also does not change the output. It evaluates the first condition, and since it's 0 (or False) is evaluates the second condition which is None.

In the second case, it first evaluates A.get('mu') and since it is not zero, it will be returned.

Look at here:
Case 1:

A = {'mu':0.1}
B = {'sigma':0.5}
x = A.get('mu') or B.get('sigma')
print(x)

Output:

0.1

it evaluates the first condition, and since it's 0.1, this will be returned.

Case 2:

A = {'mu':0.0}
B = {'sigma':0.5}
x = A.get('mu') or B.get('sigma')
print(x)  

Output:

0.5

it evaluates the first condition, and since it's 0 (or False), the second condition will be evaluated.


A possible solution (if you want to get zero as answer):

A = {'mu':0.0}
B = {'sigma':0.5}
if 'mu' in A: 
    x = A.get('mu') 
else: 
    x = B.get('sigma')
# or more compact: x = [A.get('mu') if 'mu' in A else B.get('sigma')][0]
print(x)

Output:

0.0

Upvotes: 1

Related Questions