Files
DailyChallenge_ProgrammingD…/Day_5/README.md
T
2026-08-22 01:09:25 +08:00

92 lines
2.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Day_5 · 字典:带名字的数据
> 预计耗时:20~30 分钟
> 字典是"键 → 值"的对应表。Django 里请求参数(`request.GET`)、一条数据库记录,全是字典的样子。
## 今日知识点
- 创建:`user = {"name": "张三", "age": 18}`
- 取值:`user["name"]` 或 `user.get("name")`(get 取不到不报错,可给默认值)
- 改值:`user["age"] = 19`
- 加键:`user["city"] = "青岛"`
- 删键:`del user["city"]`
- 遍历:`for k, v in user.items(): print(k, v)`
## 先学(教程)
- 菜鸟教程("字典"一节,重点看增删改查和 items()):https://www.runoob.com/python3/python3-dictionary.html
- B站黑马教程(看讲"字典"的几集):https://www.bilibili.com/video/BV1qW4y1a7fU/
## 任务(后做)
新建 `day5.py`,按顺序写并运行:
1. 创建一个"用户"字典并取值:
```python
user = {"name": "张三", "age": 18, "city": "青岛"}
print(user["name"])
print(user["age"])
```
2. 修改年龄、新增一个键、删除一个键:
```python
user["age"] = 19
user["hobby"] = "写代码"
del user["city"]
print(user)
```
3. 遍历打印每一项:
```python
for key, value in user.items():
print(f"{key} = {value}")
```
4. 用 `get()` 安全取值:
```python
print(user.get("city")) # 键已被删,会是什么?
print(user.get("city", "未知")) # 给默认值
```
5. **进阶(加分)**:造一个**字典列表**,模拟"查出来的三个用户":
```python
users = [
{"name": "张三", "age": 19},
{"name": "李四", "age": 20},
{"name": "王五", "age": 18},
]
for u in users:
print(f"{u['name']}今年{u['age']}岁")
```
## 完成标准
- [ ] 任务 1~4 输出符合预期
- [ ] 能说出 `user["x"]` 和 `user.get("x")` 的区别
- [ ] (进阶)字典列表遍历打印成功
**提交方式**:把 `day5.py` 代码贴在当日工单评论里。
## 参考解答(先做再看)
```python
user = {"name": "张三", "age": 18, "city": "青岛"}
print(user["name"]) # 张三
user["age"] = 19
user["hobby"] = "写代码"
del user["city"]
print(user) # {'name': '张三', 'age': 19, 'hobby': '写代码'}
for key, value in user.items():
print(f"{key} = {value}")
print(user.get("city")) # None(键不存在,get 不报错)
print(user.get("city", "未知")) # 未知
# 进阶
users = [
{"name": "张三", "age": 19},
{"name": "李四", "age": 20},
{"name": "王五", "age": 18},
]
for u in users:
print(f"{u['name']}今年{u['age']}岁")
```