简体   繁体   中英

Dictionary comprehension with elif in 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]}

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]}

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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM