字典 popitem() 方法
popitem() 方法用于从字典中删除随机/最后插入的项目。
在 Python 3.7 版之前,它删除随机项目,从 3.7 版开始,它删除最后插入的项目。
用法:
dictionary_name.popitem()
参数:
- 它不接受任何参数。
返回值:
这个方法的返回类型是<class 'tuple'>
,它将删除的项目作为元组(键,值)返回。
范例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.')
输出(在 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.
输出(在 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.
演示示例,如果不存在更多项目,则返回错误。
范例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.')
输出
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'
相关用法
- Python Dictionary pop()用法及代码示例
- Python Dictionary fromkeys()用法及代码示例
- Python Dictionary clear()用法及代码示例
- Python Dictionary update()用法及代码示例
- Python Dictionary setdefault()用法及代码示例
- Python Dictionary has_key()用法及代码示例
- Python Dictionary get()用法及代码示例
- Python Dictionary items()用法及代码示例
- Python Dictionary copy()用法及代码示例
- Python Dictionary keys()用法及代码示例
- Python Dictionary values()用法及代码示例
- Python Decimal shift()用法及代码示例
- Python Decimal next_plus()用法及代码示例
- Python Decimal logical_and()用法及代码示例
- Python Decimal rotate()用法及代码示例
- Python Decimal max_mag()用法及代码示例
- Python Datetime.replace()用法及代码示例
- Python Decimal as_integer_ratio()用法及代码示例
- Python DataFrame.to_excel()用法及代码示例
- Python Pandas DataFrame.fillna()用法及代码示例
注:本文由纯净天空筛选整理自 Python Dictionary popitem() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。