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爬虫爬取电影票房数据及图表展示操作示例

    Python爬虫爬取电影票房数据及图表展示操作示例

    这篇文章主要介绍了Python爬虫爬取电影票房数据及图表展示操作,结合实例形式分析了Python爬虫爬取、解析电影票房数据并进行图表展示操作相关实现技巧,需要的朋友可以参考下
    2020-03-03
  • Python中常见的文件操作合集(读取、编码和关闭)

    Python中常见的文件操作合集(读取、编码和关闭)

    这篇文章主要为大家详细介绍了Python中常见的文件操作,包括读取、编码和关闭等功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-11-11
  • Python实现快速提取PDF文档中的图片

    Python实现快速提取PDF文档中的图片

    提取PDF文档中的图片是一项常见的任务,本文将介绍如何使用PyPDF2和pdfminer.six这两个库来提取PDF文档中的图片,感兴趣的可以了解一下
    2023-06-06
  • Python使用内置函数setattr设置对象的属性值

    Python使用内置函数setattr设置对象的属性值

    这篇文章主要介绍了Python使用内置函数setattr设置对象的属性值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-10-10
  • 通过Python实现一个A/B测试详解

    通过Python实现一个A/B测试详解

    A/B测试,通过分析两种不同的营销策略,以此来选择最佳的营销策略,可以高效地将流量转化为销售额。本文主要介绍了如何通过Python实现一个A/B测试,感兴趣的可以了解一下
    2023-01-01
  • 利用python实现对excel文件进行加密

    利用python实现对excel文件进行加密

    由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴趣的小伙伴可以了解下
    2025-04-04
  • Python基本数据结构之字典类型dict用法分析

    Python基本数据结构之字典类型dict用法分析

    这篇文章主要介绍了Python基本数据结构之字典类型dict用法,结合实例形式分析了Python字典类型dict概念、原理、定义及基本使用技巧,需要的朋友可以参考下
    2019-06-06
  • 如何实现更换Jupyter Notebook内核Python版本

    如何实现更换Jupyter Notebook内核Python版本

    这篇文章主要介绍了如何实现更换Jupyter Notebook内核Python版本,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • python+selenium实现163邮箱自动登陆的方法

    python+selenium实现163邮箱自动登陆的方法

    本篇文章主要介绍了python+selenium实现163邮箱自动登陆的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12
  • 关于pandas中的.update()方法解析

    关于pandas中的.update()方法解析

    这篇文章主要介绍了关于pandas中的.update()方法解析,在Pandas中,update()方法用于将一个DataFrame或Series对象中的值更新为另一个DataFrame或Series对象中的对应值,需要的朋友可以参考下
    2023-07-07

最新评论