python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python dict key

python dict key的使用及问题小结

作者: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."

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

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() 来查看。

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).

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

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?

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?

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

您可能感兴趣的文章:
阅读全文