目录
popitem的功能popitem的用法该函数的注意事项popitem功能
删除当前字典里末尾一组键值对并将其返回popitem用法
用法:dict.popitem()
--无需传参>>
返回被删除的键值对,用元组包裹0索引是key,1索引是valueIn [44]: my_dict = { 'name' : 'insane', 'age' : 33}In [45]: my_dict.popitem()Out[45]: ( 'age', 33)
注意事项
如字典为空,则直接报错实战
# coding:utf-8students = {'insane': '到','loafer': '在','xiaoyun': '在呢','xiaogao': '在'}print('xiaogao在吗')xiaogao = students.popitem()print('{} 喊 {}'.format(xiaogao[0], xiaogao[1]))print('xiaoyun在吗')xiaoyun = students.popitem()print('{} 喊 {}'.format(xiaoyun[0], xiaoyun[1]))print('loafer在吗')loafer = students.popitem()print('{} 喊 {}'.format(loafer[0], loafer[1]))print('insane在吗')insane = students.popitem()print('{} 喊 {}'.format(insane[0], insane[1]))print(students) # 字典为空students.popitem() # 会报错
xiaogao在吗xiaogao 喊 在xiaoyun在吗xiaoyun 喊 在呢loafer在吗loafer 喊 在insane在吗insane 喊 到{}Traceback (most recent call last):File "D:/My_Files/Python Project/pythonlean/python_dict/dict_popitem.py", line 27, in <module>students.popitem() # 会报错KeyError: 'popitem(): dictionary is empty'Process finished with exit code 1