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}




Get Help

Comments

Popular posts from this blog

How To Create .ENV File in Python

Create a Large file for Test Data Processing using Python

How to solve the Liner Equation using Python