需求:遍历字典时,删除某个
key
正常情况下是不能直接删除的,需要借助其他方式:
# coding=utf-8
data = {"name": "rose", "age": 19}
# 遍历字典并删除某个 key
# 报错:RuntimeError: dictionary changed size during iteration
for k, v in data.items():
if k == "name":
data.pop(k)
优化后:
print(list(data.items())) # [('name', 'rose'), ('age', 19)]
for k, v in list(data.items()):
if k == "name":
data.pop(k)
print(data)