一、字典的创建
1)创建的时候直接初始化
student_result = {"张三": 342,"李四": 512,"王五": 412}
print(student_result["张三"])
2)创建空的字典后期添加
student_result = {}
student_result["张三"] = 300
student_result["李四"] = 400
student_result["王五"] = 500
print(student_result)
执行结果:
C:\python\python.exeC:/python/demo/file3.py
342
{'张三': 300, '李四':400, '王五': 500}
Process finished with exit code 0
二、字典的删除
如:
student_result = {"张三": 342, "李四": 512, "王五": 412}
# 方法01:pop 删除指定的元素
print(student_result)
student_result.pop("李四")
print(student_result)
# 方法02:popitem() 删除字典中最后一个元素
print(student_result)
student_result.popitem()
print(student_result)
或:
dic01 = {1: "A", 2: "B", 3: "C", 4: "D"}
print(dic01)
dic01.popitem()
print(dic01)
dic01.popitem()
print(dic01)
dic01.popitem()
print(dic01)
# 方法03:clear清空
student_result = {"张三": 342, "李四": 512, "王五": 412}
student_result.clear()
print(student_result)
问:如果使用pop删除,key不存在怎么办?程序报错,通过需要异常处理
student_result = {"张三": 342, "李四": 512, "王五": 412}
student_result.pop("ddd")
执行结果:
C:\python\python.exeC:/python/demo/file3.py
342
Traceback (most recent call last):
{'张三': 300, '李四':400, '王五': 500}
File "C:/python/demo/file3.py", line 41, in
{'张三': 342, '李四':512, '王五': 412}
{'张三': 342, '王五':412}
{'张三': 342, '王五':412}
student_result.pop("ddd")
{'张三': 342}
KeyError: 'ddd'
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}
{1: 'A', 2: 'B', 3: 'C'}
{1: 'A', 2: 'B'}
{1: 'A'}
{}
Process finished with exit code 1