Computer >> Computer tutorials >  >> Programming >> Python

How to remove a key from a python dictionary?


Python’s del keyword is used pretty much any object. In order to delete a particular item from dictionary, provide key clause to del statement

>>> D1 = {1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3}
>>> del D1['x']
>>> D1
{1: 'a', 2: 'b', 3: 'c', 'y': 2, 'z': 3}

Effect of removing a key-value pair can also be achieved by pop() method. The method takes key (and optionally value if more than one values are assigned to same key)

>>> D1 = {1: 'a', 2: 'b', 3: 'c', 'x': 1, 'y': 2, 'z': 3}
>>> D1.pop('y')
2
>>> D1
{1: 'a', 2: 'b', 3: 'c', 'x': 1, 'z': 3}