![]() |
Help: list comprehension for loop with double if statement - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Help: list comprehension for loop with double if statement (/thread-26502.html) |
Help: list comprehension for loop with double if statement - mart79 - May-04-2020 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': Thanks!
RE: Help: list comprehension for loop with double if statement - buran - May-04-2020 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/stdtypes.html#boolean-operations-and-or-not RE: Help: list comprehension for loop with double if statement - mart79 - May-04-2020 (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. 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....
RE: Help: list comprehension for loop with double if statement - buran - May-04-2020 result = [f'{case} affected' if item in (value or ()) else f'{case} unaffected' for case, value in data.items()] |