需求:对比两个字典,找出公共元素,将非公共元素删除
dict1={}
dict2={}
res=[]
for i in dict1:
if i not in dict2:
print(i)
del dict1[i]
res.append(i)
结果:报错
RuntimeError: dictionary changed size during iteration
修改代码:
dict1={"1":1,"2":2,"3":3,"4":4}
dict2={"1":1,"2":2}
res=[]
for i in list(dict1):
if i not in list(dict2):
print(i)
dict1.pop(i)
res.append(i)
print(len(res))
print(dict1)
测试结果:
dict1={'1': 1, '2': 2}