Code前端首页关于Code前端联系我们

Python 教程:字典

terry 2年前 (2023-09-27) 阅读数 65 #数据结构与算法

在 Python 字典中,每个键和值均以冒号分隔 (:),每个条目以逗号分隔 (,) 。完整的字典条目包含在大括号中。没有条目的空字典用两个大括号编写如下:{}

键在字典中是唯一的,而值可能不唯一。字典的值可以是任何类型,但键必须是不可变的数据类型,例如字符串、数字或元组。

访问字典中的值

要访问字典元素,您可以使用方括号和键来查找其值。以下是一个简单的示例 -

#!/usr/bin/python

dict = {'Name': 'Maxsu', 'Age': 27, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
Python

运行上述示例代码并得到以下结果 -

dict['Name']:  Maxsu
dict['Age']:  27
Shell

如果您尝试使用非字典键访问数据项,您将得到出现以下错误 -

#!/usr/bin/python

dict = {'Name': 'Maxsu', 'Age': 27, 'Class': 'First'}
print ("dict['Alice']: ", dict['Gender'])
Python

运行上述示例代码,得到以下结果 -

Traceback (most recent call last):
  File "F:\worksp\python\test.py", line 4, in <module>
    print ("dict['Alice']: ", dict['Gender'])
KeyError: 'Gender'
Shell

更新单词

可以通过添加新项或键值对、修改现有条目或删除现有条目 字典,如简单示例所示 -

#!/usr/bin/python

dict = {'Name': 'Maxsu', 'Age': 25, 'Class': 'First'}
dict['Age'] = 28; # update existing entry
dict['School'] = "DPS School"; # Add new entry

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Python

运行上述示例代码会得到以下结果 -

dict['Age']:  28
dict['School']:  DPS School
Shell

删除字典条目

您可以删除单个删除字典元素或清除整个词典内容。还可以一次删除整个字典。
要显式删除整个字典,只需使用语句 del 即可。下面是一个简单的例子 -

#!/usr/bin/python

dict = {'Name': 'Maxsu', 'Age': 27, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Python

运行上面的示例代码,得到以下结果 -

注意,运行del dict后,字典不再存在,所以例外是扔在这里。 -

Traceback (most recent call last):
  File "F:\worksp\python\test.py", line 8, in <module>
    print ("dict['Age']: ", dict['Age'])
TypeError: 'type' object is not subscriptable
Shell

字典键属性

字典值没有限制。它们可以是任何 Python 对象、默认对象或用户定义的对象。但是,密钥有限制。

关于字典键,需要记住两件事:

第 1 点: 每个键不能超过一个条目,这意味着不允许有重复的键。如果在分配过程中遇到重复的键,则最后分配的键优先。例如 -

#!/usr/bin/python

dict = {'Name': 'maxsu', 'Age': 27, 'Name': 'Manni'}
print ("dict['Name']: ", dict['Name'])
Python

当执行上述代码时,将产生以下结果 -

dict['Name']:  Manni
Shell

第 2 点: 键必须是不可变的。这意味着您可以使用字符串、数字或元组作为字典键,但不允许使用 ['key']。以下是一个简单的示例 -

#!/usr/bin/python

dict = {['Name']: 'Maxsu', 'Age': 27}
print ("dict['Name']: ", dict['Name'])
Python

执行上述示例代码会产生以下结果 -

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

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

热门