dict多种方法实现去除字典value为0 的元素
a = {'a': 1, 'b': 0, 'c': 3, 'd': 4, 'e': 5}
结果
a = {'a': 1, 'c': 3, 'd': 4, 'e': 5}
# 字典:value为0的移除
def removeDict():
a = {'a': 1, 'b': 0, 'c': 3, 'd': 4, 'e': 5}
# 方法1
res = {}
for key, value in a.items():
if value != 0:
res[key] = value
return res
if __name__ == '__main__':
result = removeDict()
print(result)
结果:
{'a': 1, 'c': 3, 'd': 4, 'e': 5}
from copy import deepcopy
# 字典:value为0的移除
def removeDict():
a = {'a': 1, 'b': 0, 'c': 3, 'd': 4, 'e': 5}
# 方法2
res = deepcopy(a)
for key, value in res.items():
if value == 0:
a.pop(key)
return a
if __name__ == '__main__':
result = removeDict()
print(result)
结果:
{'a': 1, 'c': 3, 'd': 4, 'e': 5}
from copy import deepcopy
# 字典:value为0的移除
def removeDict():
a = {'a': 1, 'b': 0, 'c': 3, 'd': 4, 'e': 5}
# 方法3
res = deepcopy(a)
for key, value in res.items():
if value == 0:
del a[key]
return a
if __name__ == '__main__':
result = removeDict()
print(result)
结果:
{'a': 1, 'c': 3, 'd': 4, 'e': 5}
def removeDict():
return {key: value for key, value in a.items() if value != 0}
if __name__ == '__main__':
result = removeDict()
print(result)
结果:
{'a': 1, 'c': 3, 'd': 4, 'e': 5}
通过上述四种方式实现了字典中value为0的元素删除,哪种方式更优需要自己感悟,这里不做过多的阐述;
from copy import deepcopy
# 字典:value为0的移除
def removeDict():
a = {'a': 1, 'b': 0, 'c': 3, 'd': 4, 'e': 5}
# 方法1
# b = {}
# for key, value in a.items():
# if value != 0:
# b[key] = value
# print(b)
# 方法2
# b = deepcopy(a)
# for key, value in b.items():
# if value == 0:
# a.pop(key)
# print(a)
# 方法3
# b = deepcopy(a)
# for key, value in b.items():
# if value == 0:
# del a[key]
# print(a)
# 方法4
res = {key: value for key, value in a.items() if value != 0}
print(res)
if __name__ == '__main__':
removeDict()
欢迎关注微信公众号、blibli频道:魔都吴所谓,获取更多资源分享与行业交流的信息~~~