Bird
0
0

You want to create a dictionary where keys are numbers 1 to 5 and values are "Even" or "Odd" using a ternary expression inside a dictionary comprehension. Which code is correct?

hard📝 Application Q15 of 15
Python - Conditional Statements
You want to create a dictionary where keys are numbers 1 to 5 and values are "Even" or "Odd" using a ternary expression inside a dictionary comprehension. Which code is correct?
Ad = {x: "Even" if x % 2 == 0 "Odd" for x in range(1,6)}
Bd = {x: ("Even" if x % 2 == 0 else "Odd") for x in range(1,6)}
Cd = {x if x % 2 == 0 else "Odd": x for x in range(1,6)}
Dd = {x: "Even" else "Odd" if x % 2 == 0 for x in range(1,6)}
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary comprehension syntax

    It must be {key: value for variable in iterable}. The value can use a ternary expression.
  2. Step 2: Check ternary expression placement

    d = {x: ("Even" if x % 2 == 0 else "Odd") for x in range(1,6)} correctly wraps the ternary expression in parentheses for clarity and correct parsing.
  3. Step 3: Identify incorrect options

    d = {x: "Even" if x % 2 == 0 "Odd" for x in range(1,6)} misses the else keyword, causing SyntaxError; d = {x if x % 2 == 0 else "Odd": x for x in range(1,6)} misplaces ternary in key. d = {x: "Even" else "Odd" if x % 2 == 0 for x in range(1,6)} has invalid syntax.
  4. Final Answer:

    d = {x: ("Even" if x % 2 == 0 else "Odd") for x in range(1,6)} -> Option B
  5. Quick Check:

    Use parentheses around ternary in dict comprehension [OK]
Quick Trick: Wrap ternary in parentheses inside dict comprehension [OK]
Common Mistakes:
MISTAKES
  • Placing ternary in key instead of value
  • Missing parentheses causing syntax errors
  • Using else before if in ternary

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes