"""dict_basics.py - Python 字典基础示例 包含常见的字典操作示例:创建、访问、添加、修改、删除、遍历、嵌套和推导式等。 运行后会打印每个示例的结果,并在代码中注释预期输出。 """ def main(): # 1. 创建字典 student = {"name": "Tom", "age": 18, "city": "Beijing"} print("student ->", student) # 2. 访问值 print("student['name'] ->", student["name"]) # Tom print("student['age'] ->", student["age"]) # 18 # 3. 安全获取值 print("student.get('score') ->", student.get("score")) # None print("student.get('score', 0) ->", student.get("score", 0)) # 0 # 4. 添加和修改 student["score"] = 95 student["age"] = 19 print("after add/modify ->", student) # 5. 删除键值对 del student["city"] print("after del student['city'] ->", student) # pop() 删除指定键并返回值 age = student.pop("age") print("age popped ->", age) print("after pop('age') ->", student) # 6. 判断 key 是否存在 print("'name' in student ->", "name" in student) # True print("'score' in student ->", "score" in student) # True print("'city' in student ->", "city" in student) # False # 7. 遍历字典 for key in student: print("loop key ->", key) for key, value in student.items(): print("loop item ->", key, value) for value in student.values(): print("loop value ->", value) # 8. 常见方法 print("student.keys() ->", student.keys()) print("student.values() ->", student.values()) print("student.items() ->", student.items()) print("len(student) ->", len(student)) # 9. 字典嵌套 users = { "alice": {"age": 20, "city": "Shanghai"}, "bob": {"age": 22, "city": "Hangzhou"} } print("users['alice']['city'] ->", users["alice"]["city"]) # Shanghai # 10. 字典推导式 squares = {x: x * x for x in range(1, 5)} print("squares ->", squares) # {1: 1, 2: 4, 3: 9, 4: 16} # 11. 统计频次 counts = {"apple": 3, "banana": 2} counts["apple"] += 1 print("counts ->", counts) # 12. 说明: # - 键唯一 # - 通过 key 快速查找 value # - 适合表达“映射关系” # - Python 3.7+ 保留插入顺序 if __name__ == '__main__': main()