-
Notifications
You must be signed in to change notification settings - Fork 1
/
dictionary.py
114 lines (54 loc) · 1.63 KB
/
dictionary.py
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#Initialization of Dictionary:
dict1={} #empty dictionary
dict2={1:"test",2:"rest"} #dictionary with integer keys
dict3={1:"test","name":"rest"} #dictionary with mixed type
dict4= dict({1:"test",2:"rest"}) # dictionary with dict built in function
dict5 = dict([(1,'apple'), (2,'ball')]) #from sequence having each item as a pair
#Accessing value in dictonary:
dict2={1:"test",2:"rest"}
print(dict2[2])
#output : rest
dict2={1:"test",2:"rest"}
print(dict2.get(2))
#output : rest
dict2={1:"test",2:"rest"}
print(dict2[3])
#output: print(dict2[3])
KeyError: 3
dict2={1:"test",2:"rest"}
print(dict2.get(3))
#output: None
#Adding or Changing an element in dictionary:
#updated :
dict2={1:"test",2:"rest"}
dict2[1]= "set"
print(dict2)
#output:{1: 'set', 2: 'rest'}
#Changed :
dict2={1:"test",2:"rest"}
dict2[3]= "set"
print(dict2)
#output : {1: 'test', 2: 'rest', 3: 'set'}
# Removing or deleting item from a dictionary:
dict2={1:"test",2:"rest"}
dict2.pop(2)
print(dict2)
#output :- {1: 'test'}
#popitem() :- The popitem() function removes an item from the dictionary arbitarily.
dict2={1:"test",2:"rest"}
dict2.popitem()
print(dict2)
#output :- {2: 'rest'}
#del :- It removes an individual item and also the whole dictionary.
dict2={1:"test",2:"rest"}
del dict2[2]
print(dict2)
#Output :- {1: 'test'}
dict2={1:"test",2:"rest"}
del dict2
print(dict2)
#Output :- NameError: name 'dict2' is not defined
#Dictionary membership test :-
dict2={1:"test",2:"rest"}
print(1 in dict2)
#output :- True