Remove key from dictionary python

Last Updated On Thursday 27th Jan 2022

python remove key from dictionary

  • A dictionary is a collection of unordered, modifiable(mutable) paired (key: value) data type.

To remove a key from a dictionary in Python, use the pop() method or the del keyword.Both methods work the same in that they remove keys from a dictionary.

how to remove key from dictionary python

  • As i said , We can delete a key from a Python dictionary using del keyword.
  • Because key-value pairs in dictionaries are objects, you can delete them using the del keyword.

python delete key from dict

	myDict = {'a': 1, 'b': 2, 'c': 3 }
print(myDict)

if myDict.get('b') : del myDict['b']
print(myDict)
	

python remove key from dict

	# {'a': 1, 'b': 2, 'c': 3}
# {'a': 1, 'c': 3}
	

dict pop python

Using the pop() method

	myDict = {'a': 1, 'b': 2, 'c': 3 }
print(myDict)

if myDict.get('c') : myDict.pop('c')
print(myDict)
	

remove a key from dictionary python

	# {'a': 1, 'b': 2, 'c': 3}
# {'a': 1, 'b': 2}
	

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

python dictionary pop

	myDict = {'a': 1, 'b': 2, 'c': 3}
if myDict.get('b') : var = myDict.pop('b')
print(myDict)
print(var)
	
	{'a': 1, 'c': 3}
2
	

remove key from dictionary python

Both the pop() method and the del keyword let you remove keys from a dictionary.