Skip to content

Commit 57dd405

Browse files
authored
Add files via upload
1 parent 87f4077 commit 57dd405

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

dict_comprehensions.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Python Dictionary Comprehensions
2+
# (c) Joe James 2023
3+
4+
# 1. math function to compute values using list
5+
dict1 = {x: 2*x for x in [0, 2, 4, 6]}
6+
print ('1. ', dict1)
7+
8+
# 2. math function to compute values using range
9+
dict2 = {x: x**2 for x in range(0, 7, 2)}
10+
print ('2. ', dict2)
11+
12+
# 3. from chars in a string
13+
dict3 = {x: ord(x) for x in 'Kumar'}
14+
print ('3. ', dict3)
15+
16+
# 4. given lists of keys & values
17+
x = ['Aditii', 'Brandon', 'Clumley', 'Magomed', 'Rishi']
18+
y = [1, 2, 3, 13, 18]
19+
dict4 = {i: j for (i,j) in zip(x,y)}
20+
print ('4. ', dict4)
21+
22+
# 5. from chars in a string
23+
x = "python"
24+
dict5 = {i: 3*i.upper() for i in x}
25+
print('5. ', dict5)
26+
27+
# 6. list comprehension for the value
28+
x = [2, 4, 6, 8]
29+
y = [5, 10, 15, 20]
30+
dict6 = {i: [i + 2*j for j in y] for i in x}
31+
print('6. ', dict6)
32+
33+
#7. using items
34+
x = {'A':10, 'B':20, 'C':30}
35+
dict7 = {i: j*2 for (i,j) in x.items()}
36+
print('7. ', dict7)
37+
38+
# 8. conditional comprehension
39+
dict8 = {i: i**3 for i in range(10) if i%2 == 0}
40+
print('8. ', dict8)
41+
42+
# 9. if-else conditional comprehension
43+
x = {'A':10, 'B':20, 'C':30}
44+
dict9 = {i: (j if j < 15 else j+100) for (i,j) in x.items()}
45+
print('9. ', dict9)
46+
47+
# 10. transformation from an existing dict
48+
x = {'A':10, 'B':20, 'C':30}
49+
dict10 = {i: x[i]+1 for i in x}
50+
print('10. ', dict10)
51+
52+
53+
54+

0 commit comments

Comments
 (0)