How to Remove Key-Value Pair from a JSON File in Python
Last Updated :
24 Apr, 2025
We are given a Python JSON file and our task is to remove a key-value pair in a JSON file in Python. In this article, we will see how we can remove a key-value pair in a JSON file in Python.
Remove Key-Value Pair from a JSON File in Python
Below are the possible approaches to Remove items from a JSON file In Python:
- Using the pop() method
- Using dictionary comprehension
- Using the del statement
- Using the update() method
input.json
{
"website": "GeeksforGeeks",
"topics": ["Algorithms", "Data Structures", "Python", "JavaScript"],
"featured_article": {
"title": "Introduction to JSON Parsing in Python",
"author": "GeekAuthor123",
"published_date": "2024-02-27"
}
}
Remove Key-Value Pair in a Json File Using pop() Method
In this example, we are using the pop() method to remove a specified key, "featured_article", from a JSON file (input.json). The script checks if the key exists in the JSON data before removal, and if found, it prints the removed key and its corresponding value. The updated JSON data is then saved to a new file, 'output.json', preserving the modifications made during the removal process.
Python3
import json
# load JSON data from file
with open('input.json', 'r') as file:
data = json.load(file)
# key to remove
key_to_remove = "featured_article"
# checking if the key exists before removing
if key_to_remove in data:
removed_value = data.pop(key_to_remove)
print(f"Removed key '{key_to_remove}' with value: {removed_value}")
# saving the updated JSON data back to the file
with open('output.json', 'w') as file:
json.dump(data, file, indent=2)
Output:
Removed key 'featured_article' with value: {'title': 'Introduction to JSON Parsing in Python', 'author': 'GeekAuthor123', 'published_date': '2024-02-27'}
output.json
{
"website": "GeeksforGeeks",
"topics": [
"Algorithms",
"Data Structures",
"Python",
"JavaScript"
]
}
Remove Key-Value Pair in a Json File Using Dictionary Comprehension
In this example, we are using dictionary comprehension to remove a specified key, "featured_article", from a JSON file (input.json). The script checks if the specific key exists, and removes it if found. It utilizes dictionary comprehension to create an updated dictionary without the specified key. It prints the removed key and its associated value if the key is found. Finally, the updated data is returned to a new JSON file (output.json).
Python3
import json
# load JSON data from file
with open('input.json','r') as file:
data = json.load(file)
# key to remove
key_to_remove = "featured_article"
# check if key exists
if key_to_remove in data.keys():
# Add the key if it does not equal key_to_remove
updated_data = {key : value for key, value in data.items() if key != key_to_remove }
removed_value = data[key_to_remove]
print(f"Removed key '{key_to_remove}' with value: {removed_value}")
else:
print("Key does not exist")
# Write the updated json to json file
with open('output.json','w') as f:
# write updated data
json.dump(updated_data,f,indent=2)
Output:
Removed key 'featured_article' with value: {'title': 'Introduction to JSON Parsing in Python', 'author': 'GeekAuthor123', 'published_date': '2024-02-27'}
output.json
{
"website": "GeeksforGeeks",
"topics": [
"Algorithms",
"Data Structures",
"Python",
"JavaScript"
]
}
Remove Key-Value Pair in a Json File Using del statement
In this example, we have used the del statement to remove a specified key, "featured_article", from JSON data loaded from a file named 'input.json'. The del statement deletes the key-value pair associated with the specified key in the JSON data. Finally, the updated JSON data, without the removed key, is written to a file named 'output.json'.
Python3
import json
# load JSON data from file
with open('input.json','r') as file:
data = json.load(file)
# key to remove
key_to_remove = "featured_article"
# check if key exists
if key_to_remove in data.keys():
removed_value = data[key_to_remove]
# Removing the key
del data[key_to_remove]
print(f"Removed key '{key_to_remove}' with value: {removed_value}")
else:
print("Key does not exist")
# Write the updated json to json file
with open('output.json','w') as f:
# write updated data
json.dump(data,f,indent=2)
Output:
Removed key 'featured_article' with value: {'title': 'Introduction to JSON Parsing in Python', 'author': 'GeekAuthor123', 'published_date': '2024-02-27'}
output.json
{
"website": "GeeksforGeeks",
"topics": [
"Algorithms",
"Data Structures",
"Python",
"JavaScript"
]
}
Remove Key-Value Pair Using update() Method
In this example, we have used the update method to remove a specific key, "featured_article", from the loaded JSON data from a file named 'input.json'. If the key exists, the script iterates over the data, updating a new dictionary "updated_data" with all key-value pairs except the one to be removed. Finally, it writes the updated JSON data to a file named "output.json".
Python3
import json
# load JSON data from file
with open('input.json','r') as file:
data = json.load(file)
# key to remove
key_to_remove = "featured_article"
# check if key exists
if key_to_remove in data.keys():
updated_data = {}
for key,value in data.items():
if key != key_to_remove:
updated_data.update({key : value})
else:
removed_value = value
print(f"Removed key '{key_to_remove}' with value: {removed_value}")
else:
print("Key does not exist")
# Write the updated json to json file
with open('output.json','w') as f:
# write updated data
json.dump(updated_data,f,indent=2)
Output:
Removed key 'featured_article' with value: {'title': 'Introduction to JSON Parsing in Python', 'author': 'GeekAuthor123', 'published_date': '2024-02-27'}
output.json
{
"website": "GeeksforGeeks",
"topics": [
"Algorithms",
"Data Structures",
"Python",
"JavaScript"
]
}
Similar Reads
Remove Dictionary from List If Key is Equal to Value in Python
Removing dictionaries from a list based on a specific condition is a common task in Python, especially when working with data in list-of-dictionaries format. In this article, we will see various methods to Remove Dictionary from List If the Key is Equal to the Value in Python.Using filter()filter()
2 min read
How to Extract or Parse JSON from a String in Python
Here, we are given a string and we have to parse JSON format from the string in Python using different approaches. In this article, we will see how we can parse JSON from a string in Python. Example: Input: json_string = '{"India": "Delhi", "Russia": "Moscow", "Japan": "Tokyo"}' Output: {'India': 'D
3 min read
How to Parse Json from Bytes in Python
We are given a bytes object and we have to parse JSON object from it by using different approaches in Python. In this article, we will see how we can parse JSON with bytes in Python Parse JSON With Bytes in PythonBelow are some of the ways by which we can parse JSON with bytes in Python: Using the j
4 min read
Python - Remove Dictionary if Given Key's Value is N
We are given a dictionary we need to remove key if the given value of key is N. For example, we are given a dictionary d = {'a': 1, 'b': 2, 'c': 3} we need to remove the key if the value is N so that the output becomes {'a': 1, 'c': 3}. We can use methods like del, pop and various other methods like
2 min read
Python program to extract a single value from JSON response
We will discuss how Python can be used to extract a value from a JSON response using API and JSON files.Extract Value from the JSON Response using the APIInitially, use the API Key variable to declare the base URL. Where the first currency needs to be converted with the second, ask the user to enter
3 min read
Add a key value pair to Dictionary in Python
The task of adding a key-value pair to a dictionary in Python involves inserting new pairs or updating existing ones. This operation allows us to expand the dictionary by adding new entries or modify the value of an existing key.For example, starting with dictionary d = {'key1': 'geeks', 'key2': 'fo
3 min read
Remove Nth Element from Kth key's Value from the Dictionary - Python
We are given a dictionary we need to remove the Nth element from the Kth key value. For example we are given a dictionary d = {'key1': ['a', 'b', 'c', 'd'], 'key2': ['w', 'x', 'y', 'z']} we need to remove the Nth element from the Kth key value so that the output should become {'key1': ['a', 'b', 'd'
3 min read
Python - Remove K valued key from Nested Dictionary
We are given a nested dictionary we need to remove K valued key. For example, we are given a nested dictionary d = { "a": 1, "b": {"c": 2,"d": {"e": 3,"f": 1},"g": 1},"h": [1, {"i": 1, "j": 4}]} we need to remove K valued key ( in our case we took k value as 1 ) from it so that the output should be
3 min read
Remove K Value Items from Dictionary Nesting - Python
We are given a dictionary we need to remove K value items from dictionary. For example we are having a dictionary d = {'a': {'b': 'remove', 'c': 'keep'}, 'd': {'e': 'remove', 'f': 'keep'}} we need to remove the K value suppose in this case K is 'remove' so that output should be {'a': {'c': 'keep'},
3 min read
Python Remove Item from Dictionary by Value
We are given a dictionary and our task is to remove key-value pairs where the value matches a specified target. This can be done using various approaches, such as dictionary comprehension or iterating through the dictionary. For example: d = {"a": 10, "b": 20, "c": 10, "d": 30} and we have to remove
3 min read