Junior — Middle
Can you explain how the Dict Comprehension construction works in Python?
sobes.tech AI
Answer from AI
Dict Comprehension in Python is a concise way to create a dictionary from an iterable object using an expression inside curly braces. The format is similar to list comprehension, but the result is a dictionary.
Example:
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Here, for each number from 0 to 4, a key-value pair is created, where the key is the number and the value is its square. This is convenient for quickly creating dictionaries without using a loop and explicit element addition.