-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy path007_advanced_collections.py
215 lines (167 loc) · 4.89 KB
/
007_advanced_collections.py
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "marimo",
# ]
# ///
import marimo
__generated_with = "0.10.19"
app = marimo.App()
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
# 🔄 Advanced collections
This tutorials hows advanced patterns for working with collections.
## Lists of dictionaries
A common pattern in data handling is working with lists of dictionaries:
this is helpful for representing structured data like records or entries.
"""
)
return
@app.cell
def _():
# Sample data: List of user records
users_data = [
{"id": 1, "name": "Alice", "skills": ["Python", "SQL"]},
{"id": 2, "name": "Bob", "skills": ["JavaScript", "HTML"]},
{"id": 3, "name": "Charlie", "skills": ["Python", "Java"]}
]
return (users_data,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
Let's explore common operations on structured data.
**Try it!** Try modifying the `users_data` above and see how the results
change!
"""
)
return
@app.cell
def _(users_data):
# Finding users with specific skills
python_users = [
user["name"] for user in users_data if "Python" in user["skills"]
]
print("Python developers:", python_users)
return (python_users,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
## Nested data structures
Python collections can be nested in various ways to represent complex data:
"""
)
return
@app.cell
def _():
# Complex nested structure
project_data = {
"web_app": {
"frontend": ["HTML", "CSS", "React"],
"backend": {
"languages": ["Python", "Node.js"],
"databases": ["MongoDB", "PostgreSQL"]
}
},
"mobile_app": {
"platforms": ["iOS", "Android"],
"technologies": {
"iOS": ["Swift", "SwiftUI"],
"Android": ["Kotlin", "Jetpack Compose"]
}
}
}
return (project_data,)
@app.cell
def _(project_data):
# Nested data accessing
backend_langs = project_data["web_app"]["backend"]["languages"]
print("Backend languages:", backend_langs)
ios_tech = project_data["mobile_app"]["technologies"]["iOS"]
print("iOS technologies:", ios_tech)
return backend_langs, ios_tech
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
### Example: data transformation
Let's explore how to transform and reshape collection data:
"""
)
return
@app.cell
def _():
# Data-sample for transformation
sales_data = [
{"date": "2024-01", "product": "A", "units": 100},
{"date": "2024-01", "product": "B", "units": 150},
{"date": "2024-02", "product": "A", "units": 120},
{"date": "2024-02", "product": "B", "units": 130}
]
return (sales_data,)
@app.cell
def _(sales_data):
# Transform to product-based structure
product_sales = {}
for sale in sales_data:
if sale["product"] not in product_sales:
product_sales[sale["product"]] = []
product_sales[sale["product"]].append({
"date": sale["date"],
"units": sale["units"]
})
print("Sales by product:", product_sales)
return product_sales, sale
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
## More collection utilities
Python's `collections` module provides specialized container datatypes:
```python
from collections import defaultdict, Counter, deque
# defaultdict - dictionary with default factory
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
# Counter - count hashable objects
colors = Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
print(colors.most_common(2)) # Top 2 most common colors
# deque - double-ended queue
history = deque(maxlen=10) # Only keeps last 10 items
history.append(item)
```
"""
)
return
@app.cell
def _():
from collections import Counter
# Example using Counter
programming_languages = [
"Python", "JavaScript", "Python", "Java",
"Python", "JavaScript", "C++", "Java"
]
language_count = Counter(programming_languages)
print("Language frequency:", dict(language_count))
print("Most common language:", language_count.most_common(1))
return Counter, language_count, programming_languages
@app.cell(hide_code=True)
def _(mo):
mo.md(
"""
## Next steps
For a reference on the `collections` module, see [the official Python
docs](https://docs.python.org/3/library/collections.html).
"""
)
return
@app.cell
def _():
import marimo as mo
return (mo,)
if __name__ == "__main__":
app.run()