How to remove a key from a Python dictionary?

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

    Using the "del" keyword:

    del dict[key]
    
    0 讨论(0)
  • 2020-11-22 13:13

    We can delete a key from a Python dictionary by the some following approaches.

    Using the del keyword; it's almost the same approach like you did though -

     myDict = {'one': 100, 'two': 200, 'three': 300 }
     print(myDict)  # {'one': 100, 'two': 200, 'three': 300}
     if myDict.get('one') : del myDict['one']
     print(myDict)  # {'two': 200, 'three': 300}
    

    Or

    We can do like following:

    But one should keep in mind that, in this process actually it won't delete any key from the dictionary rather than making specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict.

    myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
    {key:value for key, value in myDict.items() if key != 'one'}
    

    If we run it in the shell, it'll execute something like {'five': 500, 'four': 400, 'three': 300, 'two': 200} - notice that it's not the same ordered as myDict. Again if we try to print myDict, then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:

    var = {key:value for key, value in myDict.items() if key != 'one'}
    

    Now if we try to print it, then it'll follow the parent order:

    print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}
    

    Or

    Using the pop() method.

    myDict = {'one': 100, 'two': 200, 'three': 300}
    print(myDict)
    
    if myDict.get('one') : myDict.pop('one')
    print(myDict)  # {'two': 200, 'three': 300}
    

    The difference between del and pop is that, using pop() method, we can actually store the key's value if needed, like the following:

    myDict = {'one': 100, 'two': 200, 'three': 300}
    if myDict.get('one') : var = myDict.pop('one')
    print(myDict) # {'two': 200, 'three': 300}
    print(var)    # 100
    

    Fork this gist for future reference, if you find this useful.

    0 讨论(0)
  • 2020-11-22 13:17

    To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():

    my_dict.pop('key', None)
    

    This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (ie. my_dict.pop('key')) and key does not exist, a KeyError is raised.

    To delete a key that is guaranteed to exist, you can also use

    del my_dict['key']
    

    This will raise a KeyError if the key is not in the dictionary.

    0 讨论(0)
  • 2020-11-22 13:18

    Dictionary data type has a method called dict_name.pop(item) and this can be used to delete a key:value pair from a dictionary.

    a={9:4,2:3,4:2,1:3}
    a.pop(9)
    print(a)
    

    This will give the output as:

    {2: 3, 4: 2, 1: 3}
    

    This way you can delete an item from a dictionary in one line.

    0 讨论(0)
  • 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}
    
    0 讨论(0)
  • 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()
                )
        )
    )
    
    0 讨论(0)
提交回复
热议问题