Bird
Raised Fist0

You need to create a dictionary where keys are integers from 1 to 4 and each value is a random float between 0 and 1. Which of the following code snippets achieves this correctly?

hard🚀 Application Q8 of Q15
Python - Standard Library Usage
You need to create a dictionary where keys are integers from 1 to 4 and each value is a random float between 0 and 1. Which of the following code snippets achieves this correctly?
Aimport random result = {i: random.random() for i in range(1, 5)}
Bimport random result = {random.random(): i for i in range(1, 5)}
Cimport random result = {i: random.randint(0, 1) for i in range(1, 5)}
Dimport random result = {i: random.uniform(1, 5) for i in range(1, 5)}
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    Keys are integers from 1 to 4, values are random floats between 0 and 1.
  2. Step 2: Check each option

    import random result = {i: random.random() for i in range(1, 5)} uses a dictionary comprehension with keys from 1 to 4 and values from random.random(), which returns a float in [0.0, 1.0). This matches the requirement.
    import random result = {random.random(): i for i in range(1, 5)} incorrectly uses random.random() as keys.
    import random result = {i: random.randint(0, 1) for i in range(1, 5)} uses random.randint(0, 1), which returns integers 0 or 1, not floats.
    import random result = {i: random.uniform(1, 5) for i in range(1, 5)} uses random.uniform(1, 5), which generates floats between 1 and 5, not between 0 and 1.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Keys 1-4 with random floats 0-1? Yes. [OK]
Quick Trick: Use random.random() for floats between 0 and 1 [OK]
Common Mistakes:
MISTAKES
  • Using random.randint for floats
  • Using random.random() as keys
  • Using wrong range in random.uniform

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes