Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary comprehension with elif in Python?

Tags:

python

I am creating a dictionaries that need condition inside. So here, I have an arr_temp holding some values, and I want to set paired_vals according to element in arr_temp (now works only for one case). I tried if statement, but facing an error that I can't use elif inside a comprehension. For now I'm just adding paired_vals_mass everywhere, but it's wrong for my situation, because I have several values that complement each element in arr_temp. Can anyone suggest a good way to implement that?

report['conditions'][condname] = 
{findings: [{'name': x, 'parameters': paired_vals_mass} for x in arr_temp]}
like image 413
Alice Jarmusch Avatar asked Oct 19 '25 21:10

Alice Jarmusch


2 Answers

This is how one would implement an elif in a comprehension:

a = {x: 'negative' if x < 0 else 'positive' if x > 0 else 'zero' for x in range(-2, 2)}
print(a)  # {0: 'zero', 1: 'positive', -1: 'negative', -2: 'negative'}

As you can see, there is no elif but a nested if. Even in this simple case, the code becomes less readable.

A better option would be a selector function like so:

def selector(x):
    if x < 0:
        return 'negative'
    elif x == 0:
        return 'zero'
    else:
        return 'positive'

a = {x: selector(x) for x in range(-2, 2)}
print(a)  # {0: 'zero', 1: 'positive', -1: 'negative', -2: 'negative'}
like image 148
Ma0 Avatar answered Oct 21 '25 11:10

Ma0


It sounds like you need a function which constructs a dictionary:

def construct_dict(x, paired_vals_mass):
    ret = {'name': x}
    if x .... :
        ret['parameters'] = ...
    elif x .... :
        ret['parameters'] = ...
    else:
        ret['parameters'] = ...

    return ret

report['conditions'][condname] = 
    {findings: [construct_dict(x, paired_vals_mass) for x in arr_temp]}
like image 31
quamrana Avatar answered Oct 21 '25 09:10

quamrana