【python】dict多种方法实现去除字典value为0 的元素

题目

dict多种方法实现去除字典value为0 的元素

栗子

a = {'a': 1, 'b': 0, 'c': 3, 'd': 4, 'e': 5}

结果

a = {'a': 1, 'c': 3, 'd': 4, 'e': 5}

code

方法一:普通方法


# 字典: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}

方法二:pop方法

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}

方法三:del方法

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频道:魔都吴所谓,获取更多资源分享与行业交流的信息~~~

你可能感兴趣的:(leetcode,算法,Python,python,开发语言)