How to remove a key from a Python dictionary?

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

提交回复
热议问题