Skip to content

Commit 072903b

Browse files
sidemtzairahiramoT01majestic-owl448Dario-DC
authored
feat(curriculum): add dictionaries and sets review page (freeCodeCamp#60527)
Co-authored-by: Zaira <[email protected]> Co-authored-by: moT01 <[email protected]> Co-authored-by: Ilenia <[email protected]> Co-authored-by: Dario-DC <[email protected]>
1 parent 6bdb4e8 commit 072903b

File tree

2 files changed

+373
-5
lines changed

2 files changed

+373
-5
lines changed

client/i18n/locales/english/intro.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4142,7 +4142,7 @@
41424142
"title": "Dictionaries and Sets review",
41434143
"intro": [
41444144
"Before you're quizzed on dictionaries and sets, you should review what you've learned about them.",
4145-
"[Add more details]"
4145+
"Open up this page to review concepts around dictionaries, sets, and how to import modules."
41464146
]
41474147
},
41484148
"quiz-dictionaries-and-sets": {

curriculum/challenges/english/25-front-end-development/review-dictionaries-and-sets/67f39babe1e2ec1fb6eea32a.md

Lines changed: 372 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,381 @@ dashedName: review-dictionaries-and-sets
77

88
# --description--
99

10-
## First topic
10+
## Dictionaries
1111

12-
Describe
12+
- **Dictionaries**: Dictionaries are built-in data structures that store collections of key-value pairs. Keys need to be immutable data types. This is the general syntax of a Python dictionary:
1313

14-
## Second topic
14+
```python
15+
dictionary = {
16+
key1: value1,
17+
key2: value2
18+
}
19+
```
1520

16-
Describe
21+
- **`dict()` Constructor**: The `dict()` constructor is an alternative way to build the dictionary. You pass a list of tuples as an argument to the `dict()` constructor. These tuples contain the key as the first element and the value as the second element.
22+
23+
```python
24+
pizza = dict([('name', 'Margherita Pizza'), ('price', 8.9), ('calories_per_slice', 250), ('toppings', ['mozzarella', 'basil'])])
25+
```
26+
27+
- **Bracket Notation**: To access the value of a key-value pair, you can use the syntax known as bracket notation.
28+
29+
```python
30+
dictionary[key]
31+
```
32+
33+
## Common Dictionary Methods
34+
35+
- **`get()` Method**: The `get()` method retrieves the value associated with a key. It's similar to the bracket notation, but it lets you set a default value, preventing errors if the key doesn't exist.
36+
37+
```python
38+
dictionary.get(key, default)
39+
```
40+
41+
- **`keys()` and `values()` Methods**: The `keys()` and `values()` methods return a view object with all the keys and values in the dictionary, respectively. A view object is a way to see the content of a dictionary without creating a separate copy of the data.
42+
43+
```python
44+
pizza = {
45+
'name': 'Margherita Pizza',
46+
'price': 8.9,
47+
'calories_per_slice': 250
48+
}
49+
50+
pizza.keys()
51+
# dict_keys(['name', 'price', 'calories_per_slice'])
52+
53+
pizza.values()
54+
# dict_values(['Margherita Pizza', 8.9, 250])
55+
```
56+
57+
- **`items()` Method**: The `items()` method returns a view object with all the key-value pairs in the dictionary, including both the keys and the values.
58+
59+
```python
60+
pizza.items()
61+
# dict_items([('name', 'Margherita Pizza'), ('price', 8.9), ('calories_per_slice', 250)])
62+
```
63+
64+
- **`clear()` Method**: The `clear()` method removes all the key-value pairs from the dictionary.
65+
66+
```python
67+
pizza.clear()
68+
```
69+
70+
- **`pop()` Method**: The `pop()` method removes the key-value pair with the key specified as the first argument and returns its value. If the key doesn't exist, it returns the default value specified as the second argument. If the key doesn't exist and the default value is not specified, a `KeyError` is raised.
71+
72+
```python
73+
pizza.pop('price', 10)
74+
pizza.pop('total_price') # KeyError
75+
```
76+
77+
- **`popitem()` Method**: In Python 3.7 and above, the `popitem()` method removes the last inserted item.
78+
79+
```python
80+
pizza.popitem()
81+
```
82+
83+
- **`update()` Method**: 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. New keys will be added to the dictionary as new key-value pairs.
84+
85+
```python
86+
pizza.update({ 'price': 15, 'total_time': 25 })
87+
```
88+
89+
## Looping Over a Dictionary
90+
91+
- **Iterating Over Values**: If you need to iterate over the values in a dictionary, you can write a `for` loop with `values()` to get all the values of a dictionary.
92+
93+
```python
94+
products = {
95+
'Laptop': 990,
96+
'Smartphone': 600,
97+
'Tablet': 250,
98+
'Headphones': 70,
99+
}
100+
101+
for price in products.values():
102+
print(price)
103+
```
104+
105+
Output:
106+
107+
```md
108+
990
109+
600
110+
250
111+
70
112+
```
113+
114+
- **Iterating Over Keys**: If you need to iterate over the keys in the `products` dictionary above, you can write `products.keys()` or `products` directly.
115+
116+
```python
117+
for product in products.keys():
118+
print(product)
119+
120+
for product in products:
121+
print(product)
122+
```
123+
124+
Output:
125+
126+
```md
127+
Laptop
128+
Smartphone
129+
Tablet
130+
Headphones
131+
```
132+
133+
- **Iterating Over Key-Value Pairs**: If you need to iterate over the keys and their corresponding values simultaneously, you can iterate over `products.items()`. You get individual tuples with the keys and their corresponding values.
134+
135+
```python
136+
for product in products.items():
137+
print(product)
138+
```
139+
140+
Output:
141+
142+
```md
143+
('Laptop', 990)
144+
('Smartphone', 600)
145+
('Tablet', 250)
146+
('Headphones', 70)
147+
```
148+
149+
To store the key and value in separate loop variables, you need to separate them with a comma. The first variable stores the key, and the second stores the value.
150+
151+
```python
152+
for product, price in products.items():
153+
print(product, price)
154+
```
155+
156+
Output:
157+
158+
```md
159+
Laptop 990
160+
Smartphone 600
161+
Tablet 250
162+
Headphones 70
163+
```
164+
165+
- **`enumerate()` Function**: If you need to iterate over a dictionary while keeping track of a counter, you can call the `enumerate()` function. The function returns an `enumerate` object, which assigns an integer to each item, like a counter. You can start the counter from any number, but by default, it starts from 0.
166+
167+
Assigning the index and item to separate loop variables is the common way to use `enumerate()`. For example, with `products.items()`, you can get the entire key-value pair in addition to the index:
168+
169+
```python
170+
for index, product in enumerate(products.items()):
171+
print(index, product)
172+
```
173+
174+
Output:
175+
176+
```md
177+
0 ('Laptop', 990)
178+
1 ('Smartphone', 600)
179+
2 ('Tablet', 250)
180+
3 ('Headphones', 70)
181+
```
182+
183+
To customize the initial value of the count, you can pass a second argument to `enumerate()`. For example, here we are starting the count from 1.
184+
185+
```python
186+
for index, product in enumerate(products.items(), 1):
187+
print(index, product)
188+
```
189+
190+
Output:
191+
192+
```md
193+
1 ('Laptop', 990)
194+
2 ('Smartphone', 600)
195+
3 ('Tablet', 250)
196+
4 ('Headphones', 70)
197+
```
198+
199+
## Sets
200+
201+
- **Sets**: Sets are built-in data structures in Python that do not allow duplicate values. Sets are mutable and unordered, which means that their elements are not stored in any specific order, so you cannot use indices or keys to access them. Also, sets can only contain values of immutable data types, like numbers, strings, and tuples.
202+
203+
- **Defining a Set**: To define a set, you need to write its elements within curly brackets and separate them with commas.
204+
205+
```python
206+
my_set = {1, 2, 3, 4, 5}
207+
```
208+
209+
- **Defining an Empty Set**: If you need to define an empty set, you must use the `set()` function. Only writing empty curly braces will automatically create a dictionary.
210+
211+
```python
212+
set() # Set
213+
{} # Dictionary
214+
```
215+
216+
## Common Set Methods
217+
218+
- **`add()` Method**: You can add an element to a set with the `add()` method, passing the new element as an argument.
219+
220+
```python
221+
my_set.add(6)
222+
```
223+
224+
- **`remove()` and `discard()` Methods**: To remove an element from a set, you can either use the `remove()` method or the `discard()` method, passing the element you want to remove as an argument. The `remove()` method will raise a `KeyError` if the element is not found while the `discard()` method will not.
225+
226+
```python
227+
my_set.remove(4)
228+
my_set.discard(4)
229+
```
230+
231+
- **`clear()` method**: The `clear()` method removes all the elements from the set.
232+
233+
```python
234+
my_set.clear()
235+
```
236+
237+
## Mathematical Set Operations
238+
239+
- **`issubset()` and `issuperset()` Methods**: The `issubset()` and the `issuperset()` methods check if a set is a subset or superset of another set, respectively.
240+
241+
```python
242+
my_set = {1, 2, 3, 4, 5}
243+
your_set = {2, 3, 4, 5}
244+
245+
print(your_set.issubset(my_set)) # True
246+
print(my_set.issuperset(your_set)) # True
247+
```
248+
249+
- **`isdisjoint()` Method**: The `isdisjoint()` method checks if two sets are disjoint, if they don't have elements in common.
250+
251+
```python
252+
print(my_set.isdisjoint(your_set)) # False
253+
```
254+
255+
- **Union Operator (`|`)**: The union operator `|` returns a new set with all the elements from both sets.
256+
257+
```python
258+
my_set | your_set # {1, 2, 3, 4, 5, 6}
259+
```
260+
261+
- **Intersection Operator (`&`)**: The intersection operator `&` returns a new set with only the elements that the sets have in common.
262+
263+
```python
264+
my_set & your_set # {2, 3, 4}
265+
```
266+
267+
- **Difference Operator (`-`)**: The difference operator `-` returns a new set with the elements of the first set that are not in the other sets.
268+
269+
```python
270+
my_set - your_set # {1, 5}
271+
```
272+
273+
- **Symmetric Difference Operator (`^`)**: The symmetric difference operator `^` returns a new set with the elements that are either on the first or the second set, but not both.
274+
275+
```python
276+
my_set ^ your_set # {1, 5, 6}
277+
```
278+
279+
- **`in` Operator**: You can check if an element is in a set or not with the `in` operator.
280+
281+
```python
282+
print(5 in my_set)
283+
```
284+
285+
## Python Standard Library
286+
287+
- **Python Standard Library**: A library gives you pre-written and reusable code, like functions, classes, and data structures, that you can reuse in your projects. Python has an extensive standard library with built-in modules that implement standardized solutions for many problems and tasks. Some examples of popular built-in modules are `math``random``re` (short for "regular expressions"), and `datetime`.
288+
289+
## Import Statement
290+
291+
- **Import Statement**: To access the elements defined in built-in modules, you use an import statement. Import statements are generally written at the top of the file. Import statements work the same for functions, classes, constants, variables, and any other elements defined in the module.
292+
293+
- **Basic Import Statement**: You can use the `import` keyword followed by the name of the module:
294+
295+
```python
296+
import module_name
297+
```
298+
299+
Then, if you need to call a method from that module, you would use dot notation, with the name of the module followed by the name of the method.
300+
301+
```python
302+
module_name.method_name()
303+
```
304+
305+
For example, you would write the following in your code to import the `math` module and get the square root of 36:
306+
307+
```python
308+
import math
309+
310+
math.sqrt(36)
311+
```
312+
313+
- **Importing a Module with a Different Name**: If you need to import the module with a different name (also known as an "alias"), you can use `as` followed by the alias at the end of the import statement. This is often used for long module names or to avoid naming conflicts.
314+
315+
```python
316+
import module_name as module_alias
317+
```
318+
319+
For example, to refer to the `math` module as `m` in your code, you can assign an alias like this:
320+
321+
```python
322+
import math as m
323+
```
324+
325+
Then, you can access the elements of the module using the alias:
326+
327+
```python
328+
m.sqrt(36)
329+
```
330+
331+
- **Importing Specific Elements**: If you don't need everything from a module, you can import specific elements using `from`. In this case, the import statement starts with `from`, followed by the module name, then the `import` keyword, and finally the names of the elements you want to import.
332+
333+
```python
334+
from module_name import name1, name2
335+
```
336+
337+
Then, you can use these names without the module prefix in your Python script. For example:
338+
339+
```python
340+
from math import radians, sin, cos
341+
342+
angle_degrees = 40
343+
angle_radians = radians(angle_degrees)
344+
345+
sine_value = sin(angle_radians)
346+
cos_value = cos(angle_radians)
347+
348+
print(sine_value) # 0.6427876096865393
349+
print(cos_value) # 0.766044443118978
350+
```
351+
352+
This is helpful, but it can result in naming conflicts if you already have functions or variables with the same name. Keep it in mind when choosing which type of import statement you want to use.
353+
354+
If you need to assign aliases to these names, you can do so as well, using the `as` keyword followed by the alias.
355+
356+
```python
357+
from module_name import name1 as alias1, name2 as alias2
358+
```
359+
360+
- **Import Statement with Asterisk (`*`)**: The asterisk tells Python that you want to import everything in that module, but you want to import it so that you don't need to use the name of the module as a prefix.
361+
362+
```python
363+
from module_name import *
364+
```
365+
366+
For example, if you this to import the `math` module, you'll be able to call any function defined in that module without specifying the name of the module as a prefix.
367+
368+
```python
369+
from math import *
370+
print(sqrt(36)) # 6.0
371+
```
372+
373+
However, this is generally discouraged because it can lead to namespace collisions and make it harder to know where names come from.
374+
375+
## `if __name__ == '__main__'`
376+
377+
- **`__name__` Variable**: `__name__` is a special built-in variable in Python. When a Python file is executed directly, Python sets the value of this variable to the string `"__main__"`. But if the Python file is imported as a module into another Python script, the value of the `__name__` variable is set to the name of that module.
378+
379+
This is why you'll often find this conditional in Python scripts. It contains the code that you only want to run **only** if the Python script is running as the main program.
380+
381+
```python
382+
if __name__ == '__main__':
383+
# Code
384+
```
17385

18386
# --assignment--
19387

0 commit comments

Comments
 (0)