How to remove a key from a Python dictionary?

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

    Another way is by Using items() + dict comprehension

    items() coupled with dict comprehension can also help us achieve task of key-value pair deletion but, it has drawback of not being an inplace dict technique. Actually a new dict if created except for the key we don’t wish to include.

    test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21} 
    
    # Printing dictionary before removal 
    print ("dictionary before performing remove is : " + str(test_dict)) 
    
    # Using items() + dict comprehension to remove a dict. pair 
    # removes  vinod
    new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'} 
    
    # Printing dictionary after removal 
    print ("dictionary after remove is : " + str(new_dict)) 
    

    Output:

    dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
    dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}
    

提交回复
热议问题