Python Dictionary popitem()函数。指南

568 阅读1分钟

Python Dictionary popitem() Function Example

popitem() 函数将最后一个插入到字典中的项目删除。

Python Dictionary popitem()

Python dictionary popitem() 是一个内置的方法,用于从 dictionary 中删除一个任意的元素。它将删除 key 和 value,这意味着从 dictionary 中删除一个项目。 **popitem()**方法不接受任何参数,删除并返回任意的(key, value)对,作为一个2元组。

如果popitem()应用于一个空的dictionary,将引发一个 KeyError。在 Python 3.7 之前,popitem() 方法删除了随机元素。删除的元素是 popitem() 方法的返回值。

语法

dict_name.popitem()

参数

dictionary popitem() 方法不接受任何参数。这里,dict_name 是字典的名称。

返回值

popitem() 方法从 dictionary 中返回一个任意的元素(key 和 value)对,从 dictionary 中删除这个元素对。如果 dictionary 是空的,popitem() 方法返回一个 KeyError。

编程实例

# app.py

# Declaring a dictionary
dict1 = {'Flower': 'Rose', 'Fruit': 'Apple',
         'Bird': 'Parrot', 'Animal': 'Tiger'}
# printing the dictionary
print(dict1)
# Now we will call popitem() to remove an arbitary item
# popped item will be stored in item
item = dict1.popitem()
# Printing popped item
print(item)
# printing the new dictionary
print("After pop new dictionary is: ")
print(dict1)

输出

{'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot', 'Animal': 'Tiger'}
('Animal', 'Tiger')
After pop new dictionary is:
{'Flower': 'Rose', 'Fruit': 'Apple', 'Bird': 'Parrot'}

在这个例子中,我们可以看到我们已经声明了一个 dictionary,然后打印了这个 dictionary。

之后,我们调用 popitem() 方法从 dictionary 中取出一个任意的元素,然后我们把它存储在名为 item 的变量中。之后,我们打印了 item 和一个新的 dictionary。

dictionary popitem*()*方法有助于实现一个类似的目的。它从dictionary中删除任意键值对,并将其作为一个元组返回。

本教程就到此为止。

参见

Python dictionary items()

Python dictionary fromKeys()

Python dictionary keys()

The postPython Dictionary popitem() Function:指南首次出现在AppDividend上。