1.在循环字典时不能删除键值对,否刚会报错
删除方法:
方法一
1 dic = {'a1':'aaa','a2':'bbb','b1':'ccc'} 2 dic1 = {} 3 4 for i in dic: 5 if 'a' not in i: 6 dic1.setdefault(i,dic[i]} 7 dic = dic1 8 print(dic) //{'b1':'ccc'}
方法二:
1 dic = {'a1':'aaa','a2':'bbb','b1':'ccc'} 2 l = [] 3 for i in dic: 4 if 'a' in i: 5 l.append(i) 6 for i in l: 7 del dic[i] 8 print(dic) // {'b1':'ccc'}