python dict key的使用及问题小结

 更新时间:2026年05月24日 08:19:28   作者:Warson_L  
本文主要介绍了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."

Python Lesson: Why Dictionary Keys must be "Immutable"

教学主题:为什么字典的键(Key)必须是“不可变”的?

1. The Core Concept: Rocks vs. Clay

核心概念:石头与橡皮泥

English Explanation: In Python, every object is either "Immutable" or "Mutable."

  • Immutable (Like a Rock): Once created, you cannot change its content. If you want a different value, you must create a brand new rock. Examples: int, float, string, tuple.
  • Mutable (Like Clay): You can change, add, or remove parts of it without destroying the original object. Example: list.

中文深度解析: 在 Python 的世界里,所有数据类型可以分为两大类:“不可变”和“可变”。

  • 不可变(Immutable - 像石头): 想象你在石头上刻了一个字“5”。如果你想把它变成“6”,你没法擦掉重刻,你只能扔掉这块石头,去换一块刻着“6”的新石头。字符串、数字和元组就是这样的石头。
  • 可变(Mutable - 像橡皮泥): 列表(List)就像一块橡皮泥。你可以往里面塞一个球,或者捏掉一部分。这块橡皮泥还是原来那一块,但它的内容变了。

2. The "Address" Secret: Usingid()

内存地址的秘密:使用id()函数

Explanation: Every object in Python has a unique "Home Address" called an ID. We can use the id() function to see where Python stores our data in its memory.

Let's look at the difference:

# --- PART A: The Immutable String (The Rock) ---
print("--- String Test ---")
word = "Apple"
print(f"Value: {word}, Memory Address: {id(word)}")

# If we change 'word', Python creates a NEW address
word = "Banana"
print(f"Value: {word}, Memory Address: {id(word)}") 
# Notice: The ID changed! It's a different 'house' now.

# --- PART B: The Mutable List (The Clay) ---
print("\n--- List Test ---")
my_list = [1, 2]
print(f"Value: {my_list}, Memory Address: {id(my_list)}")

# We change the CONTENT of the list
my_list.append(3)
print(f"Value: {my_list}, Memory Address: {id(my_list)}")
# Notice: The ID is EXACTLY THE SAME! 
# The 'house' is the same, but the 'furniture' inside changed.

中文深度解析: 每个数据在电脑内存里都有一个“家庭住址”,在 Python 里用 id() 来查看。

  • 字符串实验: 当你把变量从 "Apple" 改成 "Banana" 时,你会发现 id 变了。这意味着旧的 "Apple" 被抛弃了,Python 在新地址创建了 "Banana"。这就是“不可变”——你改不了原地址的内容。
  • 列表实验: 当你给列表 append(增加)一个数字时,你会惊奇地发现 id 居然没变!这意味着“房子”还是那个房子,但里面的东西被你偷偷改了。这就是“可变”。

3. Why Dictionaries Hate Mutable Keys

为什么字典讨厌“可变”的键?

Explanation: A Dictionary is like a set of Lockers. The Key is the label on the door. To find your stuff quickly, Python turns the Key into a "fingerprint" (called a Hash).

  • If the Key is a List, you could change the list after putting it on the locker.
  • Now the "fingerprint" doesn't match anymore! Python gets lost and can't find your locker.
  • Conclusion: Python only allows Keys that never change (Immutable), so it never loses your data.

中文深度解析: 字典就像一排储物柜。**键(Key)**就是柜门上的标签。 为了能瞬间找到东西,Python 会给标签拍一张“指纹照”(这叫 Hash)。

  • 如果你用列表当标签:当你存入东西时,标签是 [1, 2]。但如果你随后偷偷把列表改成了 [1, 2, 3],虽然标签的“住址”(id) 没变,但它的“长相”变了!
  • 下次你来取东西,Python 拿着旧指纹去对,发现标签长得不一样了。Python 会抓狂:“这不科学!柜子丢了!”
  • 结论: 为了防止这种混乱,Python 强制规定:只有“不可变”的东西(指纹永远不变的)才能当字典的 Key。

4. Code Examples: Success vs. Failure

代码示例:成功与失败

# SUCCESS: Using a String (Immutable)
student = {"name": "Alice"} 

# SUCCESS: Using a Tuple (Immutable - it's a 'frozen' list)
# We will learn Tuples next! They use ()
coordinates = {(10, 20): "Hidden Treasure"}
print(coordinates[(10, 20)])

# FAILURE: Using a List (Mutable)
try:
    bad_dict = {[1, 2]: "This will crash"}
except TypeError as e:
    print(f"\nPYTHON SAYS: {e}") 
    # It says 'unhashable type: list'
    # 'Unhashable' means 'Mutable and cannot be trusted as a Key!'

5. Quiz: Are you a Python Master?

Answer the following questions based on what we learned about addresses and mutability.

Q1: Which of these can be a Dictionary Key?

  • A) [1, 2, 3]
  • B) "Python"
  • C) 99

Q2: If I have a list x = [1], and I do x.append(2), does the id(x) change? (Yes / No)

Q3: Why does Python give an error when we use a list as a Key?

  • A) Because lists are too long.
  • B) Because lists are mutable and their "fingerprint" (hash) could change.
  • C) Because lists are only for values, not keys.

到此这篇关于python dict key的使用及问题小结的文章就介绍到这了,更多相关python dict key内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python如何根据x轴、y轴坐标在坐标轴里画出曲线图

    python如何根据x轴、y轴坐标在坐标轴里画出曲线图

    这篇文章主要介绍了python如何根据x轴、y轴坐标在坐标轴里画出曲线图问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • 浅谈django 重载str 方法

    浅谈django 重载str 方法

    这篇文章主要介绍了浅谈django 重载str 方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • 一文详解python中dataclass的使用技巧

    一文详解python中dataclass的使用技巧

    dataclass是从Python3.7版本开始,作为标准库中的模块被引入,随着Python版本的不断更新,dataclass也逐步发展和完善,为Python开发者提供了更加便捷的数据类创建和管理方式,本文总结了几个我平时使用较多dataclass技巧,需要的朋友可以参考下
    2024-03-03
  • python 设置xlabel,ylabel 坐标轴字体大小,字体类型

    python 设置xlabel,ylabel 坐标轴字体大小,字体类型

    这篇文章主要介绍了python 设置xlabel,ylabel 坐标轴字体大小,字体类型,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-07-07
  • Python中常用utils库详细介绍

    Python中常用utils库详细介绍

    这篇文章主要给大家介绍了关于Python中常用utils库的相关资料,Utils是一个Python库,它提供了一系列的工具,可以帮助你更轻松地管理你的Python环境,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2024-03-03
  • 根据tensor的名字获取变量的值方式

    根据tensor的名字获取变量的值方式

    今天小编就为大家分享一篇根据tensor的名字获取变量的值方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • python自制包并用pip免提交到pypi仅安装到本机【推荐】

    python自制包并用pip免提交到pypi仅安装到本机【推荐】

    这篇文章主要介绍了python自制包并用pip免提交到pypi仅安装到本机,本文分步骤给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
    2019-06-06
  • PyTorch中loading fbgemm.dll异常的解决办法

    PyTorch中loading fbgemm.dll异常的解决办法

    PyTorch是一个深度学习框架,当我们在本地调试大模型时,可能会选用并安装它,目前已更新至2.4版本,本文给大家介绍了PyTorch中loading fbgemm.dll异常的解决办法,文中通过代码和图文介绍的非常详细,需要的朋友可以参考下
    2024-08-08
  • python中删除某个元素的方法解析

    python中删除某个元素的方法解析

    这篇文章主要介绍了python中删除某个元素的方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • 如何在Python中捕获finally语句中异常消息

    如何在Python中捕获finally语句中异常消息

    正常情况下,finally语句不会捕获异常,而是在异常处理完成后执行,那么如何在Python中捕获finally语句中异常消息呢,下面小编就来和大家详细聊聊
    2024-02-02

最新评论