python 示例_带有示例的Python字典popitem()方法

python 示例

字典popitem()方法 (Dictionary popitem() Method)

popitem() method is used to remove random/last inserted item from the dictionary.

popitem()方法用于从字典中删除随机/最后插入的项目。

Before the Python version 3.7, it removes random item and from version 3.7, it removes last inserted item.

在Python 3.7之前的版本中,它会删除随机项,而在3.7版中,它会删除最后插入的项。

Syntax:

句法:

    dictionary_name.popitem()

Parameter(s):

参数:

  • It does not accept any parameter.

    它不接受任何参数。

Return value:

返回值:

The return type of this method is <class 'tuple'>, it returns the removed item as a tuple (key, value).

此方法的返回类型为<class'tuple'> ,它以元组(键,值)的形式返回已删除的项目。

Example 1:

范例1:

# Python Dictionary popitem() Method with Example

# dictionary declaration
student = {
  "roll_no": 101,
  "name": "Shivang",
  "course": "B.Tech",
  "perc" : 98.5
}

# printing dictionary
print("data of student dictionary...")
print(student)

# removing item
x = student.popitem()
print(x, ' is removed.')

# removing item
x = student.popitem()
print(x, ' is removed.')

Output (On Python version 3)

输出(在Python版本3上)

data of student dictionary...
{'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5, 'roll_no': 101}
('name', 'Shivang')  is removed.
('course', 'B.Tech')  is removed.

Output (On Python version 3.7.4)

输出(在Python版本3.7.4上)

data of student dictionary...
{'roll_no': 101, 'name': 'Shivang', 'course': 'B.Tech', 'perc': 98.5}
('perc', 98.5)  is removed.
('course', 'B.Tech')  is removed.

Demonstrate the example, if no more item exists then it returns an error.

演示该示例,如果不存在任何其他项目,则返回错误。

Example 2:

范例2:

# Python Dictionary popitem() Method with Example

# dictionary declaration
temp = {
  "key1": 1,
  "key2": 2
}

# printing dictionary
print("data of temp dictionary...")
print(temp)

# popping item
x = temp.popitem()
print(x, 'is removed.')

# popping item
x = temp.popitem()
print(x, 'is removed.')

# popping item
x = temp.popitem()
print(x, 'is removed.')

Output

输出量

data of temp dictionary...
{'key2': 2, 'key1': 1}
('key2', 2) is removed.
('key1', 1) is removed.
Traceback (most recent call last):
  File "main.py", line 22, in <module>
    x = temp.popitem()
KeyError: 'popitem(): dictionary is empty'


翻译自: https://www.includehelp.com/python/dictionary-popitem-method-with-example.aspx

python 示例

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值