BudiBadu Logo

Map Numbers to Their Squares

Python Easy 17 views

Learn Python dictionary comprehensions to efficiently create dictionaries from sequences. You will transform a list of items into a dictionary with computed keys and values, demonstrating how to build mappings in a single, readable expression.

Your task is to create a dictionary comprehension that processes input data and generates key-value pairs based on specific transformation rules. Focus on clarity and conciseness while ensuring the logic is immediately understandable.

Example 1:

Input: numbers = [1, 2, 3, 4, 5]
Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation: Create dictionary where key is the number and value is its square.

Example 2:

Input: words = ["cat", "dog", "bird"]
Output: {"cat": 3, "dog": 3, "bird": 4}
Explanation: Map each word to its length.

Example 3:

Input: numbers = [1, 2, 3]
Output: {2: 4, 4: 16}
Explanation: Only include even numbers after doubling them as keys, squared as values.

Algorithm Flow

Recommendation Algorithm Flow for Map Numbers to Their Squares - Budibadu
Recommendation Algorithm Flow for Map Numbers to Their Squares - Budibadu

Best Answers

python - Approach 1
def create_dict(items):
    result = {}
    for x in items:
        result[x] = x * x
    return result