python dict key详解

A Dictionary Key must be like a permanent ID card. If the ID card can change its name or numbers, Python will lose track of where your data is stored."


1. The "Rock" vs. "Clay" Analogy

Explanation:

  • Immutable (Rocks): Things like Strings, Integers, and Tuples. Once you create them, you cannot change them. They are solid like rocks.
  • Mutable (Clay): Things like Lists. You can add, remove, or change items inside a list. It's like a piece of clay you can reshape.

中文解释:

  • 不可变(石头): 比如字符串、数字和元组。一旦创建就不能改了,像石头一样硬。
  • 可变(橡皮泥): 比如列表。你可以增加、删除或修改里面的元素,像橡皮泥一样可以变形。

2. Example: Why Strings and Numbers work (Success)

Strings and numbers are Immutable. They never change their value.

python 复制代码
# --- EXAMPLE 1: Using Strings and Numbers ---

# This works perfectly because "Alice" will always be "Alice"
student_scores = {
    "Alice": 95, 
    "Bob": 88,
    101: "Room A"  # Numbers are also immutable
}

print(student_scores["Alice"]) # Python finds it easily!

# Explanation: 
# "Alice" is a string. You cannot change "Alice" into "Alicia" 
# without creating a whole new string. It is safe as a Key.

中文解释: 字符串和数字是"不可变"的。因为 "Alice" 永远是 "Alice",不会突然变成别的东西,所以 Python 能轻松通过这个 Key 找到对应的值。


3. Example: Why Lists fail (The Error)

Lists are Mutable. Because they can change, Python refuses to use them as Keys.

python 复制代码
# --- EXAMPLE 2: Trying to use a List (This will CRASH) ---

# Imagine we want to use a list of coordinates as a key
try:
    my_list = [1, 2]
    treasure_map = {my_list: "Golden Statue"}
except TypeError as e:
    print(f"Error: {e}")

# Explanation: 
# If Python allowed this, and you did: my_list.append(3)
# The key would change from [1, 2] to [1, 2, 3].
# Now Python wouldn't know where the "Golden Statue" is!
# That's why Python gives a "TypeError: unhashable type: 'list'".

中文解释: 列表是"可变的"。如果你把列表 [1, 2] 当做 Key,万一你后面执行了 append(3),Key 就变样了。Python 会觉得这太不安全了,所以直接报错,不让你这么干。


4. Example: Using Tuples (The "Frozen List")

Since the child is about to learn Tuples , this is a great time to show that a Tuple is just an Immutable version of a List.

python 复制代码
# --- EXAMPLE 3: Using a Tuple (The Solution) ---

# A Tuple uses () instead of []
# It is IMMUTABLE (cannot be changed after creation)
point = (1, 2)

locations = {
    point: "Home",
    (5, 10): "School"
}

print(locations[(1, 2)]) # This works!

# Explanation:
# Because you CANNOT add or change items in a Tuple, 
# it is "solid" enough to be a Dictionary Key.

中文解释: 元组(Tuple)使用圆括号 ()。它就像一个"被冻住"的列表,一旦写好就不能改了。因为它是"不可变"的,所以它是安全的,可以作为字典的 Key。


Summary Table for the Student

Data Type Mutable? (Can change?) Can be a Dict Key?
String ❌ No (Immutable) ✅ Yes
Integer ❌ No (Immutable) ✅ Yes
Tuple ❌ No (Immutable) ✅ Yes
List ✅ Yes (Mutable) ❌ No

You can tell the student:

"Python is very organized. It only wants keys that it can trust to stay the same forever. If a key can change (like a List), Python says: 'Nope, too messy!'"

相关推荐
jay神38 分钟前
2026年YOLO还有哪些创新点可以做?
python·yolo·毕业设计·科研·课程设计·创新
傲笑风9 小时前
【openvino】tinybert基于openvino服务化部署(四)
人工智能·python·自然语言处理·nlp·bert·openvino
维基框架10 小时前
WIKI 知识库 v1.1.1 正式发布
人工智能·python
谢白羽13 小时前
SGLang的AWQ量化笔记
笔记·python·sglang
迷迭香yy14 小时前
基金档案数据工程实战从收入分析到持仓穿透的Python解析 IG50免费开源股票数据API接口
开发语言·python
清水白石00814 小时前
Python 类型设计深度解析:TypedDict 能否替代 dataclass?从 JSON 数据边界到 API 设计的最佳实践
java·python·json
️学习的小王15 小时前
Git项目提交忽略文件怎么做?以Python项目为例,详解.gitignore
git·python·elasticsearch
前端 贾公子15 小时前
第09章:上下文与记忆 (6)
开发语言·前端·python
evans在进步15 小时前
Java 常用设计模式入门:建造者、工厂、单例、外观与代理
java·python·设计模式
jayson.h15 小时前
PDF 合并+添加页码 相关库、类、函数
开发语言·前端·python