Dict Comprehension in Python
Code Example
Example 1:
d = {i:i for i in range(1, 6)}
print(d)
Output: {1: 1, 2: 2, 3: 3, 4: 4, 5: 5}
Example 2:
d = {i:[i, i+1] for i in range(6)}
print(d)
Output: {0: [0, 1], 1: [1, 2], 2: [2, 3], 3: [3, 4], 4: [4, 5], 5: [5, 6]}
Example 3:
d = {i:i**2 for i in range(6)}
print(d)
Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Comments
Post a Comment