Haleshot commited on
Commit
ce9e994
·
unverified ·
1 Parent(s): be305c4

Add interactive notebook for Python dictionaries with examples and operations

Browse files
Files changed (1) hide show
  1. Python/phase_3/dictionaries.py +254 -0
Python/phase_3/dictionaries.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "marimo",
5
+ # ]
6
+ # ///
7
+
8
+ import marimo
9
+
10
+ __generated_with = "0.10.14"
11
+ app = marimo.App()
12
+
13
+
14
+ @app.cell
15
+ def _():
16
+ import marimo as mo
17
+ return (mo,)
18
+
19
+
20
+ @app.cell(hide_code=True)
21
+ def _(mo):
22
+ mo.md(
23
+ """
24
+ # 📚 Python Dictionaries
25
+
26
+ Welcome to the world of Python dictionaries — where data gets organized with keys!
27
+
28
+ ## Creating Dictionaries
29
+ Dictionaries are collections of key-value pairs. Here's how to create them:
30
+
31
+ ```python
32
+ simple_dict = {"name": "Alice", "age": 25} # direct creation
33
+ empty_dict = dict() # empty dictionary
34
+ from_pairs = dict([("a", 1), ("b", 2)]) # from key-value pairs
35
+ ```
36
+
37
+ Below is a sample dictionary we'll use to explore operations.
38
+ """
39
+ )
40
+ return
41
+
42
+
43
+ @app.cell
44
+ def _():
45
+ sample_dict = {
46
+ "name": "Python",
47
+ "type": "programming language",
48
+ "year": 1991,
49
+ "creator": "Guido van Rossum",
50
+ "is_awesome": True
51
+ }
52
+ return (sample_dict,)
53
+
54
+
55
+ @app.cell(hide_code=True)
56
+ def _(mo):
57
+ mo.md(
58
+ """
59
+ ## Basic Dictionary Operations
60
+
61
+ Let's explore how to work with dictionaries.
62
+ Try modifying the `sample_dict` above and watch how the results change!
63
+ """
64
+ )
65
+ return
66
+
67
+
68
+ @app.cell
69
+ def _(sample_dict):
70
+ # Accessing values of the dictionary
71
+ def access_dict():
72
+ print(f"Name: {sample_dict['name']}")
73
+ print(f"Year: {sample_dict['year']}")
74
+ access_dict()
75
+ return (access_dict,)
76
+
77
+
78
+ @app.cell
79
+ def _(sample_dict):
80
+ # Safe access with get()
81
+ def safe_access():
82
+ print(f"Version: {sample_dict.get('version', 'Not specified')}")
83
+ print(f"Type: {sample_dict.get('type', 'Unknown')}")
84
+ safe_access()
85
+ return (safe_access,)
86
+
87
+
88
+ @app.cell(hide_code=True)
89
+ def _(mo):
90
+ mo.md("""
91
+ ## Dictionary Methods
92
+
93
+ Python dictionaries come with powerful built-in methods:
94
+ """)
95
+ return
96
+
97
+
98
+ @app.cell
99
+ def _(sample_dict):
100
+ # Viewing dictionary components
101
+ def view_components():
102
+ print("Keys:", list(sample_dict.keys()))
103
+ print("Values:", list(sample_dict.values()))
104
+ print("Items:", list(sample_dict.items()))
105
+ view_components()
106
+ return (view_components,)
107
+
108
+
109
+ @app.cell
110
+ def _():
111
+ # Modifying dictionaries
112
+ def demonstrate_modification():
113
+ _dict = {"a": 1, "b": 2}
114
+ print("Original:", _dict)
115
+
116
+ # Adding/updating
117
+ _dict.update({"c": 3, "b": 22})
118
+ print("After update:", _dict)
119
+
120
+ # Removing
121
+ _removed = _dict.pop("b")
122
+ print(f"Removed {_removed}, Now:", _dict)
123
+ demonstrate_modification()
124
+ return (demonstrate_modification,)
125
+
126
+
127
+ @app.cell(hide_code=True)
128
+ def _(mo):
129
+ mo.md("""
130
+ ## Dictionary Comprehension
131
+
132
+ Create dictionaries efficiently with dictionary comprehensions:
133
+ """)
134
+ return
135
+
136
+
137
+ @app.cell
138
+ def _():
139
+ # Dictionary comprehension examples
140
+ def demonstrate_comprehension():
141
+ # Squares dictionary
142
+ _squares = {x: x**2 for x in range(5)}
143
+ print("Squares:", _squares)
144
+
145
+ # Filtered dictionary
146
+ _even_squares = {x: x**2 for x in range(5) if x % 2 == 0}
147
+ print("Even squares:", _even_squares)
148
+ demonstrate_comprehension()
149
+ return (demonstrate_comprehension,)
150
+
151
+
152
+ @app.cell(hide_code=True)
153
+ def _(mo):
154
+ mo.md("""
155
+ ## Nested Dictionaries
156
+
157
+ Dictionaries can contain other dictionaries, creating complex data structures:
158
+ """)
159
+ return
160
+
161
+
162
+ @app.cell
163
+ def _():
164
+ nested_data = {
165
+ "users": {
166
+ "alice": {
167
+ "age": 25,
168
+ "email": "[email protected]",
169
+ "interests": ["python", "data science"]
170
+ },
171
+ "bob": {
172
+ "age": 30,
173
+ "email": "[email protected]",
174
+ "interests": ["web dev", "gaming"]
175
+ }
176
+ }
177
+ }
178
+ return (nested_data,)
179
+
180
+
181
+ @app.cell
182
+ def _(nested_data):
183
+ # Accessing nested data
184
+ def access_nested():
185
+ print("Alice's age:", nested_data["users"]["alice"]["age"])
186
+ print("Bob's interests:", nested_data["users"]["bob"]["interests"])
187
+
188
+ # Safe nested access
189
+ def _get_nested(data, *keys, default=None):
190
+ _current = data
191
+ for _key in keys:
192
+ if isinstance(_current, dict):
193
+ _current = _current.get(_key, default)
194
+ else:
195
+ return default
196
+ return _current
197
+
198
+ print("\nSafe access example:")
199
+ print("Charlie's age:", _get_nested(nested_data, "users", "charlie", "age", default="Not found"))
200
+ access_nested()
201
+ return (access_nested,)
202
+
203
+
204
+ @app.cell(hide_code=True)
205
+ def _(mo):
206
+ mo.md("""
207
+ ## Common Dictionary Patterns
208
+
209
+ Here are some useful patterns when working with dictionaries:
210
+
211
+ ```python
212
+ # Pattern 1: Counting items
213
+ counter = {}
214
+ for item in items:
215
+ counter[item] = counter.get(item, 0) + 1
216
+
217
+ # Pattern 2: Grouping data
218
+ groups = {}
219
+ for item in _items:
220
+ key = get_group_key(item)
221
+ groups.setdefault(key, []).append(item)
222
+
223
+ # Pattern 3: Caching/Memoization
224
+ cache = {}
225
+ def expensive_function(arg):
226
+ if arg not in cache:
227
+ cache[arg] = compute_result(arg)
228
+ return cache[arg]
229
+ ```
230
+ """)
231
+ return
232
+
233
+
234
+ @app.cell(hide_code=True)
235
+ def _(mo):
236
+ callout_text = mo.md("""
237
+ ## Master the Dictionary!
238
+
239
+ Next Steps:
240
+
241
+ - Practice different dictionary methods
242
+ - Try creating nested data structures
243
+ - Experiment with dictionary comprehensions
244
+ - Build something using common patterns
245
+
246
+ Keep organizing your data! 🗂️✨
247
+ """)
248
+
249
+ mo.callout(callout_text, kind="success")
250
+ return (callout_text,)
251
+
252
+
253
+ if __name__ == "__main__":
254
+ app.run()