Map Numbers to Their Squares
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

Best Answers
def create_dict(items):
result = {}
for x in items:
result[x] = x * x
return resultComments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this problem.
