不仅是字典,列表同样会。
例如:将dic字典中含有’k‘的键删除
dic = {'k1':'v1','k2':'v2','a3':'v3'} for i in dic: if 'k' in i: del dic[i] print(dic)
输出报错:
它虽然删除了第一个,但是之后开始报错
{'k2': 'v2', 'a3': 'v3'} Traceback (most recent call last): File "D:/PycharmProjects/untitled/day7/数据类型汇总.py", line 48, in <module> for i in dic: RuntimeError: dictionary changed size during iteration
解决办法:将含有'k'的键值单独拿出来创建一个列表,再通过列表元素循环删除字典中的键;或者将不含有’k‘的键值重新创建一个新的字典
dic = {'k1':'v1','k2':'v2','a3':'v3'} dic1 = {} for i in dic.keys(): if 'k' not in i: dic1 = dic1.setdefault(i,dic[i]) print(dic1) ''' li = [] for i in dic.keys(): if 'k' in i: li.append(i) for i1 in li: if 'k' in i1: del dic[i1] print(dic) '''