Python 字典的删除

目录

  • clear函数的功能与用法
  • pop函数的功能与用法
  • del在字典中的用法

clear功能

  • 清空当前的字典中所有数据

clear用法

  • 用法: dict.clear() ->无参数,无返回值
In [23]: my_dict = { ' name' : 'insane' , 'age' : 33}
In [24]: my_dict.clear()
In [25]: print(my_dict)
{}

pop功能

  • 删除字典中指定的key,并将其结果返回,如果key不存在则报错

pop用法

  • 用法∶
    • dict.pop(key) – key希望被删掉的键
    • >>返回这个key对应的值( value )
In [26]: my_dict = { 'name': 'insane' , 'age' :33}
In [27]: pop_value = my_dict.pop( 'age' )
In [28]: print( 'pop value: ', pop_value, 'my_dict: ' , my_dict)
pop value: 33 my_dict: { 'name': 'insane'}

del在字典中的用法

my_dict = {'name': 'insane', 'age': 33}
del my_dict['name']
print(my_dict)
>> {'age': 33}

del my_dict
print(my_dict) ->报错,整个字典对象已被删除

实战

# coding: utf-8

projects = {
    'ipad': {'name': 'ipad', 'price': 2000, 'desc': '平板电脑'},
    'iphone': {'name': 'iphone', 'price': 3000, 'desc': '智能手机'},
    'pc': {'name': 'pc', 'price': 5000, 'desc': '台式电脑'},
    'mac': {'name': 'mac', 'price': 8000, 'desc': '苹果电脑'}
}

print(projects.keys())
print('一个中学生购买了{},价格是{}'.format(projects['pc']['name'], projects['pc']['price']))
projects.pop('pc')
print(projects.keys())

result = projects.pop('mac')
print('一个程序员构面了{},价格是{}'.format(result['name'], result.get('price')))
print(projects.keys())

print('{}和{}都被卖出了,它们一共花费了{}元'.format(
    projects['ipad']['name'],projects['iphone']['name'],
    projects['ipad']['price']+projects['iphone']['price']
))
projects.clear()
print(projects.keys())

del projects
print(projects)  # 会报错
dict_keys(['ipad', 'iphone', 'pc', 'mac'])
一个中学生购买了pc,价格是5000
dict_keys(['ipad', 'iphone', 'mac'])
一个程序员构面了mac,价格是8000
dict_keys(['ipad', 'iphone'])
ipad和iphone都被卖出了,它们一共花费了5000元
dict_keys([])
Traceback (most recent call last):
  File "D:/My_Files/Python Project/pythonlean/python_dict/dict_del.py", line 27, in 
    print(projects)  # 会报错
NameError: name 'projects' is not defined

Process finished with exit code 1

你可能感兴趣的:(Python全栈,python,列表,字典)