Bird
0
0

What will this Python code output?

medium📝 Analysis Q4 of 15
AI for Everyone - How AI Models Actually Work
What will this Python code output?
training_data = ['green', 'green', 'yellow']
counts = {}
for color in training_data:
    counts[color] = counts.get(color, 0) + 1
print(counts)
A{'green': 1, 'yellow': 2}
B{'green': 2, 'yellow': 1}
C{'green': 3, 'yellow': 0}
D{'green': 0, 'yellow': 1}
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the loop

    For each color, the code increments its count in the dictionary.
  2. Step 2: Count occurrences

    'green' appears twice, 'yellow' once.
  3. Final Answer:

    {'green': 2, 'yellow': 1} -> Option B
  4. Quick Check:

    Count matches occurrences in list [OK]
Quick Trick: Dictionary counts items using get() with default zero [OK]
Common Mistakes:
  • Mixing counts of different items
  • Forgetting to initialize counts
  • Assuming counts reset each iteration

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More AI for Everyone Quizzes