Python 如何从字典中删除键

Python 如何从字典中删除键

在Python中,字典是一种无序的数据集合,用于存储数据值,例如map,与其他仅存储单个值的数据类型不同。字典的键必须是唯一的和不可变的数据类型,如字符串,整数和元组,但键值可以重复并且可以是任何类型。字典是可变的,因此在定义字典之后可以添加或删除键。

有多种方法可以从字典中删除键,以下是几种方法。

使用pop(key,d)

pop(key, d) 方法从字典中返回一个键的值。它接受两个参数:要删除的键和一个可选的值,如果找不到该键,则返回该值。

示例1

以下是使用所需的键参数弹出一个元素的示例。

#creating a dictionary with key value pairs
#Using the pop function to remove a key
dict = {1: "a", 2: "b"}
print(dict)
dict.pop(1)
#printing the dictionary after removing a key

输出

执行上述程序后会产生以下输出。

{1: 'a', 2: 'b'}

示例2

在下面的示例中,通过将弹出的值赋给一个变量来访问弹出的键值。

#creating a dictionary with key value pairs
#Using the pop function to remove a key
dict = {1: "a", 2: "b"}
print(dict)
value=dict.pop(1)
#printing the dictionary after removing a key
print(dict)
#printing the popped value
print(value)

输出

执行以上程序后,将生成以下输出结果。

{1: 'a', 2: 'b'}
{2: 'b'}
a

示例3

下面是一个示例,展示了使用 del() 函数从字典中删除键。与使用 pop() 不同,使用del()函数无法返回任何值。

#creating a dictionary with key value pairs
#Using the pop function to remove a key
dict = {1: "a", 2: "b"}
print(dict)
del(dict[1])
#printing the dictionary after removing a key
print(dict)

输出

在执行上述程序时,会产生以下输出。

{1: 'a', 2: 'b'}
{2: 'b'}

使用字典生成式

前面的技术在使用字典时更新它,这意味着键值对会被删除。如果我们需要保留原始键,可以使用自定义函数实现。

在Python中,众所周知列表生成式可以从现有列表构建新列表。我们可以使用字典生成式来执行相同的操作。与从列表中删除条目不同,我们可以使用字典生成式创建一个新字典,并使用条件排除我们不想要的值。

示例

以下示例演示了使用字典生成式从Python字典中删除一个键的过程。

dict = {1: "a", 2: "b"}
#printing dictionary before deletion
print(dict)
dict2 = {k: i for k, i in dict.items() if k != 1}
#printing new dictionary
print("dictionary after dictionary comprehension")
print(dict2)

输出

执行上述程序后生成以下输出。

{1: 'a', 2: 'b'}
dictionary after dictionary comprehension
{2: 'b'}

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程