Skip to content

Commit 79338df

Browse files
majestic-owl448zairahiraDario-DC
authored
feat: add dictionaries and sets lectures (freeCodeCamp#61303)
Co-authored-by: Zaira <[email protected]> Co-authored-by: Dario-DC <[email protected]>
1 parent a8cfb66 commit 79338df

File tree

4 files changed

+789
-160
lines changed

4 files changed

+789
-160
lines changed

curriculum/challenges/english/25-front-end-development/lecture-working-with-dictionaries-and-sets/683ec7a722bc7b67c1132bd3.md

Lines changed: 174 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -7,127 +7,261 @@ dashedName: what-are-dictionaries-and-how-do-they-work
77

88
# --description--
99

10-
Lecture text
10+
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.
45+
46+
```python
47+
pizza = dict([('name', 'Margherita Pizza'), ('price', 8.9), ('calories_per_slice', 250), ('toppings', ['mozzarella', 'basil'])])
48+
```
49+
50+
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:
91+
92+
```python
93+
pizza.get('toppings', []) # ['mozzarella', 'basil']
94+
```
95+
96+
The `.keys()` and `.values()` methods return a view object with all the keys and values in the dictionary, respectively:
97+
98+
```python
99+
pizza.keys()
100+
# dict_keys(['name', 'price', 'calories_per_slice'])
101+
102+
pizza.values()
103+
# dict_values(['Margherita Pizza', 8.9, 250])
104+
```
105+
106+
A view object is just a way to see the content of a dictionary without creating a separate copy of the data.
107+
108+
The `.items()` method returns a view object with all the key-value pairs in the dictionary, including both the keys and the values:
109+
110+
```python
111+
pizza.items()
112+
# dict_items([('name', 'Margherita Pizza'), ('price', 8.9), ('calories_per_slice', 250)])
113+
```
114+
115+
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.
11157

12158
# --questions--
13159

14160
## --text--
15161

16-
Question 1
162+
How are elements primarily organized and accessed in a Python dictionary?
17163

18164
## --answers--
19165

20-
Answer 1.1
166+
Using sequential indices, like a list.
21167

22168
### --feedback--
23169

24-
Feedback 1
170+
Think about the core characteristic that distinguishes dictionaries from lists and tuples.
25171

26172
---
27173

28-
Answer 1.2
29-
30-
### --feedback--
31-
32-
Feedback 1
174+
Using key-value pairs, where keys are unique.
33175

34176
---
35177

36-
Answer 1.3
178+
Using a tree-like structure, similar to file systems.
37179

38180
### --feedback--
39181

40-
Feedback 1
182+
Think about the core characteristic that distinguishes dictionaries from lists and tuples.
41183

42184
---
43185

44-
Answer 1.4
186+
Using a linked list, where elements point to the next.
45187

46188
### --feedback--
47189

48-
Feedback 1
190+
Think about the core characteristic that distinguishes dictionaries from lists and tuples.
49191

50192
## --video-solution--
51193

52-
5
194+
2
53195

54196
## --text--
55197

56-
Question 2
198+
What is the primary characteristic of a Python dictionary that makes it different from a list or tuple?
57199

58200
## --answers--
59201

60-
Answer 2.1
202+
Dictionaries create duplicates of all key-value pairs.
61203

62204
### --feedback--
63205

64-
Feedback 2
206+
Think about the feature that makes dictionaries particularly helpful for data retrieval based on names or labels.
65207

66208
---
67209

68-
Answer 2.2
210+
Dictionaries are mutable.
69211

70212
### --feedback--
71213

72-
Feedback 2
214+
Think about the feature that makes dictionaries particularly helpful for data retrieval based on names or labels.
73215

74216
---
75217

76-
Answer 2.3
77-
78-
### --feedback--
79-
80-
Feedback 2
218+
Dictionaries allow fast lookups using keys.
81219

82220
---
83221

84-
Answer 2.4
222+
Dictionaries can store duplicate values.
85223

86224
### --feedback--
87225

88-
Feedback 2
226+
Think about the feature that makes dictionaries particularly helpful for data retrieval based on names or labels.
89227

90228
## --video-solution--
91229

92-
5
230+
3
93231

94232
## --text--
95233

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?
97235

98236
## --answers--
99237

100-
Answer 3.1
238+
`.keys()`
101239

102240
### --feedback--
103241

104-
Feedback 3
242+
Think about which method is designed for safe retrieval of values without throwing an error.
105243

106244
---
107245

108-
Answer 3.2
246+
`.values()`
109247

110248
### --feedback--
111249

112-
Feedback 3
250+
Think about which method is designed for safe retrieval of values without throwing an error.
113251

114252
---
115253

116-
Answer 3.3
254+
`.pop()`
117255

118256
### --feedback--
119257

120-
Feedback 3
258+
Think about which method is designed for safe retrieval of values without throwing an error.
121259

122260
---
123261

124-
Answer 3.4
125-
126-
### --feedback--
127-
128-
Feedback 3
262+
`.get()`
129263

130264
## --video-solution--
131265

132-
5
266+
4
133267

0 commit comments

Comments
 (0)