Python Forum

Full Version: Help: list comprehension for loop with double if statement
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have the following piece if code which I want to write more cleanly using list comprehension.
However, I am struggling with the list comprehension using the double if statement in the for loop.
Can somebody help me with this?

data = {'caseA': ['Printers'], 'caseB': None, 'caseC': ['Printers', 'Computers'], 'caseD': None, 'caseE': None}
item = 'Printers'

relations = ''

if data:
    for case in data:
        if data[case] is not None:
            if item in data[case]:
                label = 'affected'
            else:
                label = 'unaffected'
        else:
            label = 'unaffected'

        relations = relations + label + ','
I have this:
if data:
   label = ['unaffected' if data[case] is None else 'affected' for case in data if item in data[case]]
but it results in an error related to 'None':
Error:
label = ['unaffected' if data[case] is None else 'affected' for case in data if current_element in data[case]] TypeError: argument of type 'NoneType' is not iterable
Thanks!
data = {'caseA': ['Printers'], 'caseB': None, 'caseC': ['Printers', 'Computers'], 'caseD': None, 'caseE': None}
item = 'Printers'

result = ['affected' if item in (value or ()) else 'unaffected' for value in data.values()]
print(', '.join(result))
of course, it could also be oneliner.
Further reading: https://docs.python.org/3/library/stdtyp...and-or-not
(May-04-2020, 06:22 AM)buran Wrote: [ -> ]
data = {'caseA': ['Printers'], 'caseB': None, 'caseC': ['Printers', 'Computers'], 'caseD': None, 'caseE': None}
item = 'Printers'

result = ['affected' if item in (value or ()) else 'unaffected' for value in data.values()]
print(', '.join(result))
of course, it could also be oneliner.
Further reading: https://docs.python.org/3/library/stdtyp...and-or-not

Thanks buran for your swift reply!

Small addition, is there any way to get the name of the dictionary key in the result?
I mean....

Output:
caseA affected, caseB unaffected, caseC affected, caseD unaffected, caseE unaffected
result = [f'{case} affected' if item in (value or ()) else f'{case} unaffected' for case, value in data.items()]