Python Forum
Help: list comprehension for loop with double if statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help: list comprehension for loop with double if statement
#3
(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
Reply


Messages In This Thread
RE: Help: list comprehension for loop with double if statement - by mart79 - May-04-2020, 06:32 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List Comprehension Issue johnywhy 5 546 Jan-14-2024, 07:58 AM
Last Post: Pedroski55
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 493 Oct-17-2023, 09:46 AM
Last Post: tomciodev
Photo Python code: While loop with if statement HAMOUDA 1 583 Sep-18-2023, 11:18 AM
Last Post: deanhystad
  Using list comprehension with 'yield' in function tester_V 5 1,264 Apr-02-2023, 06:31 PM
Last Post: tester_V
  Multiply and Addition in the same loop statement with logic. joelraj 2 1,046 Feb-02-2023, 04:33 AM
Last Post: deanhystad
  list comprehension 3lnyn0 4 1,426 Jul-12-2022, 09:49 AM
Last Post: DeaD_EyE
  List Creation and Position of Continue Statement In Regular Expression Code new_coder_231013 3 1,681 Jun-15-2022, 12:00 PM
Last Post: new_coder_231013
  List comprehension used differently coder_sw99 3 1,739 Oct-03-2021, 04:12 PM
Last Post: coder_sw99
  Change a list to integer so I can use IF statement buckssg 3 2,254 Sep-21-2021, 02:58 AM
Last Post: bowlofred
  How to invoke a function with return statement in list comprehension? maiya 4 2,867 Jul-17-2021, 04:30 PM
Last Post: maiya

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020