forked from arvimal/100DaysofCode-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21-dictionaries.py
More file actions
59 lines (48 loc) · 1.37 KB
/
21-dictionaries.py
File metadata and controls
59 lines (48 loc) · 1.37 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
#!/usr/bin/env python3
# Dictionaries map a value to a key, hence a value can be
# called using the key.
# 1. They ar3333i3ie mutable, ie. they can be changed.
# 3. They are surrounded by curly {} brackets.
# 3. They are indexed using square [] brackets.
# 4. Key and Value pairs are separated by columns ":"
# 5. Each pair of key/value pairs are separated by commas ",".
# 6. Dicts return values not in any order.
# 7. collections.OrderedDict() gives an ordered dictionary.
# Create a dict
mydict1 = {}
# Add values to the dict.
mydict1["host1"] = "A.B.C.D"
mydict1["host2"] = "E.F.G.H"
print(mydict1)
# Remove values
del mydict1["host2"]
print(mydict1)
# Check if a key exists in a dict.
"host2" in mydict1
"host1" in mydict1
# Add elements to the dictionary
mydict1["host3"] = "I.J.K.L"
mydict1["host4"] = "M.N.O.P"
print(mydict1)
# Check the length of the dictionary
print(len(mydict1))
print(mydict1.keys())
released = {
"IPhone": 2007,
"IPhone 3G": 2008,
"IPhone 3GS": 2009,
"IPhone 4": 2010,
"IPhone 4S": 2011,
"IPhone 5": 2012,
"IPhone 5s": 2013,
"IPhone SE": 2016,
}
for i, j in released.items():
print("{0} was released in {1}".format(i, j))
# Change a value for a specific key
print("Changing the value for a key")
released["IPhone"] = 2006
released["IPhone"] += 1
print(released["IPhone"])
released["IPhone"] -= 1
print(released["IPhone"])