Python 中字典键的属性


字典值没有限制。它们可以是任何任意的 Python 对象,无论是标准对象还是用户自定义对象。然而,键并不如此。

关于字典键有两个重要要点——

  • 不允许每个键有多个条目。这意味着不允许重复键。分配期间遇到重复键时,最后的分配获胜。

示例

以下是一个简单的例子——

 动态演示

#!/usr/bin/python
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']

输出

当执行以上代码时,它会产生以下结果——

dict['Name']: Manni
  • 键必须是不可变的。这意味着你可以使用字符串、数字或元组作为字典键,但诸如 ['key'] 的内容是不允许的。

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

示例

以下是一个简单的例子——

 动态演示

#!/usr/bin/python
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']

输出

当执行以上代码时,它会产生以下结果——

Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'

更新日期: 28-1 月-2020

4K+ 浏览量

开启您的 职业生涯

完成课程获得认证

马上开始
广告