将字典中所有带‘a’的键值删除

dic = {'a1':'he','a2':'ma','a3':'ye','height':20,'sex':'male'}
#把KEY转换成列表,再遍历列表
for key in list(dic.keys()):
    if 'a' in key:
        dic.pop(key)
print(dic)
#创建新列表,再遍历列表删除字典中对应的键
dic = {'a1':'he','a2':'ma','a3':'ye','height':20,'sex':'male'}
li1 = []
for key in dic:
    if 'a' in key:
        li1.append(key)
for x in li1:
    dic.pop(x)
print(dic)
#坑,报错,字典在迭代期间改变了大小,列表也有类似的报错
dic = {'a1':'he','a2':'ma','a3':'ye','height':20,'sex':'male'}
for key,value in dic.items():
    if 'a' in key:
        dic.pop(key)
print(dic)

 

posted @ 2020-03-27 13:05  河马哥  阅读(270)  评论(0编辑  收藏  举报