You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: curriculum/challenges/english/25-front-end-development/lecture-working-with-dictionaries-and-sets/683ec7a722bc7b67c1132bd3.md
In Python, dictionaries are built-in data structures that store collections of key-value pairs. They work very similarly to real dictionaries, where you search for a word to find its corresponding meaning.
11
+
12
+
With Python dictionaries, you use a key to find its corresponding value. You should use dictionaries when you need to associate values to unique keys. This is helpful when you need to find a value fast based on the key, and when you need to represent structured data.
13
+
14
+
This is the general syntax of a Python dictionary:
15
+
16
+
```python
17
+
dictionary = {
18
+
key1: value1,
19
+
key2: value2
20
+
}
21
+
```
22
+
23
+
First, we find the variable that holds the dictionary. You don't necessarily need to assign the dictionary to a variable, but it's very common to do this to keep it in memory and use it later in the code.
24
+
25
+
Then that's followed by curly braces, which are sometimes called curly brackets. And within the curly braces, there are key-value pairs.
26
+
27
+
Each key is associated with a value, so you can use the key to access that value. After each value, except the last one, there's a comma to separate the different key-value pairs. Keys must be unique in the dictionary, and they must be an immutable data type. However, the values can be repeated, and they can be of any data type.
28
+
29
+
Here we have an example of a dictionary that stores information about a Margherita pizza recipe:
30
+
31
+
```python
32
+
pizza = {
33
+
'name': 'Margherita Pizza',
34
+
'price': 8.9,
35
+
'calories_per_slice': 250,
36
+
'toppings': ['mozzarella', 'basil']
37
+
}
38
+
```
39
+
40
+
The dictionary is assigned to the `pizza` variable. It has four key-value pairs: `name`, `price`, `calories_per_slice`, and `toppings`.
41
+
42
+
Another alternative would be using the `dict()` constructor, which builds the dictionary from a sequence of key-value pairs.
43
+
44
+
This would be the equivalent syntax for our pizza example. We pass a list of tuples as argument to the `dict()` constructor. These tuples contain the key as the first element and the value as the second element.
To access the value of a key-value pair, you can use this syntax, known as bracket notation. It's the name of the variable that holds the dictionary, followed by square brackets, and the key you want to access within the square brackets:
51
+
52
+
```python
53
+
dictionary[key]
54
+
```
55
+
56
+
In our pizza example, if you want to access the value of `name`, you would write the name of the variable, `pizza`, followed by square brackets, and the key, `name`, within quotes:
57
+
58
+
```python
59
+
pizza['name']
60
+
```
61
+
62
+
This will evaluate to:
63
+
64
+
```python
65
+
'Margherita Pizza'
66
+
```
67
+
68
+
To update a value, you just need to add the assignment operator, followed by the new value.
69
+
70
+
If the key doesn't exist in the dictionary, a new key-value pair will be created. In recent versions of Python, dictionaries preserve the order of insertion. This is helpful when you need to iterate over the dictionary:
71
+
72
+
```python
73
+
pizza['name'] ='Margherita'
74
+
```
75
+
76
+
Now the value of the key `name` is `'Margherita'`:
77
+
78
+
```python
79
+
print(pizza['name']) # 'Margherita'
80
+
```
81
+
82
+
Dictionaries also have helpful methods to perform common operations.
83
+
84
+
The `.get()` method retrieves the value associated with a key. It's similar to the bracket notation that we just used, but its advantage is that you can set a default value, so you won't get an error is the key doesn't exist:
85
+
86
+
```python
87
+
dictionary.get(key, default)
88
+
```
89
+
90
+
In this example, if the `toppings` key doesn't exist, it will return an empty list, which is the default value that we are passing here as the second argument. But if `toppings` does exist, it will return that value:
The `.clear()` method removes all the key-value pairs from the dictionary:
116
+
117
+
```python
118
+
pizza.clear()
119
+
```
120
+
121
+
The `.pop()` method removes the key-value pair with the key that you specify as the first argument and returns its value. If the key doesn't exist, it returns the default value that you specify as the second argument. If the key doesn't exist and you don't pass a default value, a `KeyError` is raised:
122
+
123
+
```python
124
+
pizza.pop('price', 10)
125
+
pizza.pop('total_price') # KeyError
126
+
```
127
+
128
+
In Python 3.7 and more recent versions, the `.popitem()` method removes the last inserted item:
129
+
130
+
```python
131
+
pizza.popitem()
132
+
```
133
+
134
+
And finally, the `.update()` method updates the key-value pairs with the key-value pairs of another dictionary. If they have keys in common, their values are overwritten.
135
+
136
+
In this example, we are updating the `pizza` dictionary. The `price` key exists in both of them, so its value will be replaced with `15`.
137
+
138
+
But `total_time` is new, so it will be added to the `pizza` dictionary as a new key-value pair:
139
+
140
+
```python
141
+
pizza.update({ 'price': 15, 'total_time': 25 })
142
+
```
143
+
144
+
This is the new dictionary with the updated `price` and the new `total_time`. Notice how the price is now `15` and `total_time` is a new key-value pair:
145
+
146
+
```python
147
+
{
148
+
'name': 'Margherita Pizza',
149
+
'price': 15,
150
+
'calories_per_slice': 250,
151
+
'toppings': ['mozzarella', 'basil'],
152
+
'total_time': 25
153
+
}
154
+
```
155
+
156
+
These are some of the most commonly used dictionary methods, but there are many more. Choosing the right one can be helpful for performing complex operations efficiently.
11
157
12
158
# --questions--
13
159
14
160
## --text--
15
161
16
-
Question 1
162
+
How are elements primarily organized and accessed in a Python dictionary?
17
163
18
164
## --answers--
19
165
20
-
Answer 1.1
166
+
Using sequential indices, like a list.
21
167
22
168
### --feedback--
23
169
24
-
Feedback 1
170
+
Think about the core characteristic that distinguishes dictionaries from lists and tuples.
25
171
26
172
---
27
173
28
-
Answer 1.2
29
-
30
-
### --feedback--
31
-
32
-
Feedback 1
174
+
Using key-value pairs, where keys are unique.
33
175
34
176
---
35
177
36
-
Answer 1.3
178
+
Using a tree-like structure, similar to file systems.
37
179
38
180
### --feedback--
39
181
40
-
Feedback 1
182
+
Think about the core characteristic that distinguishes dictionaries from lists and tuples.
41
183
42
184
---
43
185
44
-
Answer 1.4
186
+
Using a linked list, where elements point to the next.
45
187
46
188
### --feedback--
47
189
48
-
Feedback 1
190
+
Think about the core characteristic that distinguishes dictionaries from lists and tuples.
49
191
50
192
## --video-solution--
51
193
52
-
5
194
+
2
53
195
54
196
## --text--
55
197
56
-
Question 2
198
+
What is the primary characteristic of a Python dictionary that makes it different from a list or tuple?
57
199
58
200
## --answers--
59
201
60
-
Answer 2.1
202
+
Dictionaries create duplicates of all key-value pairs.
61
203
62
204
### --feedback--
63
205
64
-
Feedback 2
206
+
Think about the feature that makes dictionaries particularly helpful for data retrieval based on names or labels.
65
207
66
208
---
67
209
68
-
Answer 2.2
210
+
Dictionaries are mutable.
69
211
70
212
### --feedback--
71
213
72
-
Feedback 2
214
+
Think about the feature that makes dictionaries particularly helpful for data retrieval based on names or labels.
73
215
74
216
---
75
217
76
-
Answer 2.3
77
-
78
-
### --feedback--
79
-
80
-
Feedback 2
218
+
Dictionaries allow fast lookups using keys.
81
219
82
220
---
83
221
84
-
Answer 2.4
222
+
Dictionaries can store duplicate values.
85
223
86
224
### --feedback--
87
225
88
-
Feedback 2
226
+
Think about the feature that makes dictionaries particularly helpful for data retrieval based on names or labels.
89
227
90
228
## --video-solution--
91
229
92
-
5
230
+
3
93
231
94
232
## --text--
95
233
96
-
Question 3
234
+
Which dictionary method is used to retrieve a value associated with a key, and provide a default value if the key is not found?
97
235
98
236
## --answers--
99
237
100
-
Answer 3.1
238
+
`.keys()`
101
239
102
240
### --feedback--
103
241
104
-
Feedback 3
242
+
Think about which method is designed for safe retrieval of values without throwing an error.
105
243
106
244
---
107
245
108
-
Answer 3.2
246
+
`.values()`
109
247
110
248
### --feedback--
111
249
112
-
Feedback 3
250
+
Think about which method is designed for safe retrieval of values without throwing an error.
113
251
114
252
---
115
253
116
-
Answer 3.3
254
+
`.pop()`
117
255
118
256
### --feedback--
119
257
120
-
Feedback 3
258
+
Think about which method is designed for safe retrieval of values without throwing an error.
0 commit comments