Bird
Raised Fist0

You want to generate a dictionary where keys are numbers from 1 to 5 and values are random integers between 10 and 20. Which code correctly does this?

hard🚀 Application Q15 of Q15
Python - Standard Library Usage
You want to generate a dictionary where keys are numbers from 1 to 5 and values are random integers between 10 and 20. Which code correctly does this?
Aimport random result = {i: random.randint(10, 20) for i in range(1, 6)}
Bimport random result = {random.randint(10, 20): i for i in range(1, 6)}
Cimport random result = {i: random.choice(range(10, 20)) for i in range(1, 6)}
Dimport random result = dict(random.randint(10, 20) for i in range(1, 6))
Step-by-Step Solution
Solution:
  1. Step 1: Understand dictionary comprehension syntax

    We want keys as numbers 1 to 5 and values as random integers between 10 and 20. The syntax is {key: value for key in iterable}.
  2. Step 2: Check each option

    import random result = {i: random.randint(10, 20) for i in range(1, 6)} correctly uses i as key and random.randint(10, 20) as value for each i in 1 to 5.
    import random result = {random.randint(10, 20): i for i in range(1, 6)} swaps keys and values incorrectly.
    import random result = {i: random.choice(range(10, 20)) for i in range(1, 6)} uses random.choice(range(10, 20)) which produces integers 10-19 excluding 20, unlike randint(10,20).
    import random result = dict(random.randint(10, 20) for i in range(1, 6)) tries to convert a generator of integers to dict, which causes an error.
  3. Final Answer:

    import random result = {i: random.randint(10, 20) for i in range(1, 6)} -> Option A
  4. Quick Check:

    Correct dict comprehension with randint [OK]
Quick Trick: Use dict comprehension with randint for random values [OK]
Common Mistakes:
MISTAKES
  • Swapping keys and values
  • Using dict() on generator of ints
  • Using choice with range(10,20) excludes 20

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes