How to remove a key from a Python dictionary?

后端 未结 13 1733
-上瘾入骨i
-上瘾入骨i 2020-11-22 12:37

When deleting a key from a dictionary, I use:

if \'key\' in my_dict:
    del my_dict[\'key\']

Is there a one line way of doing this?

13条回答
  •  心在旅途
    2020-11-22 13:20

    Single filter on key

    • return "key" and remove it from my_dict if "key" exists in my_dict
    • return None if "key" doesn't exist in my_dict

    this will change my_dict in place (mutable)

    my_dict.pop('key', None)
    

    Multiple filters on keys

    generate a new dict (immutable)

    dic1 = {
        "x":1,
        "y": 2,
        "z": 3
    }
    
    def func1(item):
        return  item[0]!= "x" and item[0] != "y"
    
    print(
        dict(
            filter(
                lambda item: item[0] != "x" and item[0] != "y", 
                dic1.items()
                )
        )
    )
    

提交回复
热议问题