--- fid: 20251025-135301 title: Dict Set Default Tutorial Examples tags: dict, dict setdefault --- # Dict Set Default Tutorial Examples (date: 2025-10-25) **难度**: 2 **时长**: 30 min 这是[Dict Set Default Tutorial](dict-set-default-tutorial.md) 的代码记录。 ## 场景1:按类别分组 ```python # 将学生按班级分组 students = [('Alice', 'A'), ('Bob', 'B'), ('Charlie', 'A')] classes = {} for name, class_name in students: classes.setdefault(class_name, []).append(name) # 结果: {'A': ['Alice', 'Charlie'], 'B': ['Bob']} ``` ## 场景2:计数 ```python # 统计单词频率 words = ['apple', 'banana', 'apple', 'orange'] counter = {} for word in words: counter.setdefault(word, 0) += 1 # 结果: {'apple': 2, 'banana': 1, 'orange': 1} ``` ## 场景3:构建嵌套结构 ```python # 构建城市-人名的嵌套字典 data = [('London', 'Alice'), ('Paris', 'Bob'), ('London', 'Charlie')] city_people = {} for city, name in data: city_people.setdefault(city, {})[name] = True # 结果: {'London': {'Alice': True, 'Charlie': True}, 'Paris': {'Bob': True}} ``` ## 场景4:提供默认配置 ```python # 填充配置默认值 user_config = {'color': 'blue'} # 用户只提供了颜色 defaults = {'color': 'red', 'size': 'medium', 'theme': 'light'} # 用默认值填充缺失的配置项,但不覆盖现有值 for key, value in defaults.items(): user_config.setdefault(key, value) # 结果: {'color': 'blue', 'size': 'medium', 'theme': 'light'} ``` 每个示例都展示了`setdefault`如何用一行代码优雅地处理"检查-初始化-使用"的模式。