-
Notifications
You must be signed in to change notification settings - Fork 0
/
12. Dictionary.py
74 lines (57 loc) · 1.18 KB
/
12. 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
# A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
# store data values in key:value pairs
# curly brackets
# Accessing Items
dic = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# by referring to key name, inside square brackets
x = dic["model"]
# get()
x = dic.get("model")
# Get Keys
x = dic.keys()
# or
for key in dic:
print(key)
for x in dic.keys():
print(x)
# Get Values
x = dic.values()
for i in dic:
print(dic[i])
# return a view object
for x in dic.values():
print(x)
# Get Items, as a list of tuples
x = dic.items()
for x, y in dic.items():
print(x, y)
# Check if Key Exists
if "model" in dic:
print("Yes")
# Get default if key not found
dic.get("luv", "Not a valid key")
# -----------------
# Add New index key and value
dic["color"] = 'red'
# Change Values update
# If the item does not exist, the item will be added
dic.update({"year": 2020})
# -----------------
# Removes the last inserted item
dic.popitem()
# Removing Items
dic.pop("model")
del dic["year"]
# Empties the dictionary
dic.clear()
del dic
# ----------------
# Make copy
mydict = dic.copy()
mydict2 = dict(dic)
# Dictionary Length
len(dict)