删除两个字典中非公共的键和值
需求:对比两个字典,找出公共元素,将非公共元素删除
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}
本文介绍了一种方法来对比两个字典,并找出它们之间的公共元素。通过删除非公共元素,确保了最终字典仅包含两字典共有的键值对。文章通过示例代码展示了如何避免迭代过程中修改字典导致的运行时错误。
3万+

被折叠的 条评论
为什么被折叠?



