How to remove a key from a Python dictionary?

后端 未结 13 1439
-上瘾入骨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:19

    I prefer the immutable version

    foo = {
        1:1,
        2:2,
        3:3
    }
    removeKeys = [1,2]
    def woKeys(dct, keyIter):
        return {
            k:v
            for k,v in dct.items() if k not in keyIter
        }
    
    >>> print(woKeys(foo, removeKeys))
    {3: 3}
    >>> print(foo)
    {1: 1, 2: 2, 3: 3}
    

提交回复
热议问题