Repository navigation
Expand file tree
/
Copy path06_dictionaries.py
More file actions
140 lines (104 loc) · 2.12 KB
/
Copy path06_dictionaries.py
File metadata and controls
140 lines (104 loc) · 2.12 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
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# Dictionaries
band = {
"vocals": "Plant",
"guitar": "Page"
}
band2 = dict(vocals="Plant", guitar="Page")
print(band)
print(band2)
print(type(band))
print(len(band))
# Access items
print(band["vocals"])
print(band["guitar"])
# list all keys
print(band.keys())
# list all values
print(band.values())
# list of key / value pair as tuples
print(band.items())
# verify a key exist
print("vocals" in band)
print("triangle" in band)
# change value
band["vocals"] = "Coverdale"
band.update({"bass": "JPG"})
print(band)
# remove items
print(band.pop("bass"))
print(band)
band["drums"] = "Bonham"
print(band)
print(band.popitem()) # tuple
print(band)
# delete and clear
band["drums"] = "Bonham"
del band["drums"]
print(band)
band2.clear()
print(band2)
del band2
# dictionaries copy
band2 = band.copy()
band2["drums"] = "Dave"
print("Good copy !")
print(band)
print(band2)
# or use dict() constructor function
band3 = dict(band)
print("Good copy !")
print(band3)
# Nested dictionaries
number1 = {
"name": "Plant",
"instrument": "Vocals"
}
number2 = {
"name": "Page",
"instrument": "Guidar"
}
band = {
"number1": number1,
"number2": number2
}
print(band)
print(band["number1"]["name"])
# Sets
nums = {1, 2, 3, 4}
nums2 = set((1,2,3,4))
print(nums)
print(nums2)
print(type(nums))
print(len(nums))
# no duplicate allowed
nums = {1, 2, 2, 3, 4}
print(nums)
# True is a dupe of 1 and False is a dupe of zero
nums = {1, True, 2, False, 3, 0}
print(nums)
# check a value is in a Set
print(2 in nums)
# but you cannot refer to an element in the set with an index porition or a key
# Add a new element to a set
nums.add(8)
print(nums)
# add element from one set to another
morenums = {5, 6, 7}
nums.update(morenums)
print(nums)
# you can use update with lists, tuples, and dictionaris, too.
# Merge two sets to create a new set
one = {1, 2, 3}
two = {4, 5, 6}
mynewset = one.union(two)
[print(mynewset)]
# keep only the duplicates
one = {1, 2, 3}
two = {2, 3, 4}
one.intersection_update(two)
print(one)
# keep everything except the duplicates
one = {1, 2, 3}
two = {2, 3, 4}
one.symmetric_difference_update(two)
print(one)