-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdict_comprehensions.py
More file actions
77 lines (42 loc) · 1.32 KB
/
Copy pathdict_comprehensions.py
File metadata and controls
77 lines (42 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# create a dictionary with word and its length pair
sentence = "hello good afternoon"
words = sentence.split()
d = {}
for word in words:
d[word] = len(word)
print(d)
# comprehension
d = {word: len(word) for word in words}
print(d)
#############################################################################
# create a dictionary with word and its length pair only if it is of even length
sentence = "hello good afternoon"
words = sentence.split()
d = {}
for word in words:
if len(word) % 2 != 0:
d[word] = len(word)
print(d)
d = {word: len(word) for word in words if len(word) % 2 != 0}
print(d)
########################################################################
# index and word -> if the word is even, keep it as it is else reverse it
sentence = "hello good afternoon"
words = sentence.split()
d = {}
# using range()
for i in range(len(words)):
if len(words[i]) % 2 == 0:
d[i] = words[i]
else:
d[i] = words[i][::-1]
# using enumerate()
for index, item in enumerate(words):
if len(item) % 2 == 0:
d[index] = item
else:
d[index] = item[::-1]
print(d)
# comprehension
d = {index: item if len(item) % 2 == 0 else item[::-1] for index, item in enumerate(words)}
print(d)