data = {'IP': {'key1': 'val1', 'key2': 'val2'}}
lst = ['IP', 'key1']

current_level = data
for key in lst[:-1]:
    current_level = current_level[key]
current_level.pop(lst[-1])

Explanation

I'll use the more complex example you provided to explain how this works. The first part of the task is to get to the dictionary from which the key should actually be removed.

{
  'IP': {
    'key1': {
      'key3': {
        'key4': 'val4',
        'key5': 'val5'
        }
      },
    'key2': 'val2'
    }
}

path = ['IP', 'key1', 'key3', 'key4']

In this example, in order to remove the key 'key4', we first need to get to the dictionary that contains this key, which is the dictionary under 'key3'. If we had this specific dictionary in a variable, say d, we could just call d.pop('key4').

'key3': {
  'key4': 'val4',
   'key5': 'val5'
  }

The path to this dictionary is data['IP']['key1']['key3']. The algorithm, instead of going directly like this, starts at the root dictionary and goes one level deeper with every iteration of the for loop. So, after the first iteration current_level is data['IP']. After the next one, it becomes data['IP']['key1']. (Because since current_level is already data['IP'], current_level = current_level['key1'] is indeed the same as data['IP']['key1'].)

This process is repeated until the needed dictionary is found. That means doing this for every element in the list that specifies the path, instead of the last one, because the last one is no more a dictionary, but a key in the dictionary that we search for. (lst[:1] is Python's way of saying all elements from lst except the last one.)

Then finally, we simply pop the necessary key (the last element in the list, in other words lst[-1]) from the dictionary to which it actually belongs, the one the algorithm found in the first step.

Answer from Filip Müller on Stack Overflow
Top answer
1 of 5
2
data = {'IP': {'key1': 'val1', 'key2': 'val2'}}
lst = ['IP', 'key1']

current_level = data
for key in lst[:-1]:
    current_level = current_level[key]
current_level.pop(lst[-1])

Explanation

I'll use the more complex example you provided to explain how this works. The first part of the task is to get to the dictionary from which the key should actually be removed.

{
  'IP': {
    'key1': {
      'key3': {
        'key4': 'val4',
        'key5': 'val5'
        }
      },
    'key2': 'val2'
    }
}

path = ['IP', 'key1', 'key3', 'key4']

In this example, in order to remove the key 'key4', we first need to get to the dictionary that contains this key, which is the dictionary under 'key3'. If we had this specific dictionary in a variable, say d, we could just call d.pop('key4').

'key3': {
  'key4': 'val4',
   'key5': 'val5'
  }

The path to this dictionary is data['IP']['key1']['key3']. The algorithm, instead of going directly like this, starts at the root dictionary and goes one level deeper with every iteration of the for loop. So, after the first iteration current_level is data['IP']. After the next one, it becomes data['IP']['key1']. (Because since current_level is already data['IP'], current_level = current_level['key1'] is indeed the same as data['IP']['key1'].)

This process is repeated until the needed dictionary is found. That means doing this for every element in the list that specifies the path, instead of the last one, because the last one is no more a dictionary, but a key in the dictionary that we search for. (lst[:1] is Python's way of saying all elements from lst except the last one.)

Then finally, we simply pop the necessary key (the last element in the list, in other words lst[-1]) from the dictionary to which it actually belongs, the one the algorithm found in the first step.

2 of 5
0

Maybe something like this:

def get(d, lst):
    for i in range(len(lst) - 1):
        d = d[lst[i]]
    d.pop(lst[-1])
    return data


print(get(data, lst))

Output:

{'IP': {'key2': 'val2'}}
🌐
W3Schools
w3schools.com › python › ref_dictionary_pop.asp
Python Dictionary pop() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... car = { "brand": "Ford", "model": "Mustang", "year": 1964 } car.pop("model") print(car) Try it Yourself »
Discussions

how to delete json object using python? - Stack Overflow
I am using python to delete and update a JSON file generated from the data provided by user, so that only few items should be stored in the database. I want to delete a particular object from the J... More on stackoverflow.com
🌐 stackoverflow.com
Why does in my code json pop dont work? (In python) - Stack Overflow
Let me explain my problem! I code a Python Discord Bot and it saves the channel id and the owner id! And if the ticket got closed it need to pop ticket! My code looks so: with open("data/tickets. More on stackoverflow.com
🌐 stackoverflow.com
python - How do I pop the [List] after reading the JSON URL? - Stack Overflow
Then loop through the posts and delete (pop out) any posts made by the user with a userId of 5. Write the resulting JSON (with posts deleted) to a local file. More on stackoverflow.com
🌐 stackoverflow.com
September 18, 2021
Alternative to JSON loads?
Like converting from a string to json using json.loads function I get a dictionary that I have to reference like myobject['toplevelattr']['secondlevelattr']['thirdlevelattr'] What else would it be? Unlike maps in Java, dictionaries in Python are a high-performing collection type with a lot of useful features and strong paradigms for access and iteration. The problem with this is its very easy to write a typo on one of these dictionary field references and you don't know it until some runtime error pops up. Yeah, it's Python. All errors are runtime errors. Are you expecting type guarantees from a dynamically-typed language? Why can't it produce a series of objects like Jackson, and we can refer like myobject.toplevelattr.secondlevelattr.thirdlevelattr. Because that would be pointless? Object attributes are determined at runtime, same as dictionary keys. You'd still only get your error in runtime, only it would be AttributeError instead of KeyError. If your keys are known in advance, then why not just define them as constants? Then you get an access pattern like my_object[TOPATTR][SECONDATTR][THIRDATTR] #or whatever you want. More on reddit.com
🌐 r/learnpython
16
1
April 8, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-remove-key-value-pair-from-a-json-file-in-python
How to Remove Key-Value Pair from a JSON File in Python - GeeksforGeeks
July 23, 2025 - Using the pop() method · Using ... "published_date": "2024-02-27" } } In this example, we are using the pop() method to remove a specified key, "featured_article", from a JSON file (input.json)....
🌐
Like Geeks
likegeeks.com › home › python › remove elements from json arrays in python
Remove Elements from JSON arrays in Python
January 22, 2024 - Also, you can use pop() with a specific index to remove an element from any position in the JSON array: second_package_removed = packages.pop(1) print(second_package_removed) print(packages) ...
Top answer
1 of 5
29

Here's a complete example that loads the JSON file, removes the target object, and then outputs the updated JSON object to file.

#!/usr/bin/python                                                               

# Load the JSON module and use it to load your JSON file.                       
# I'm assuming that the JSON file contains a list of objects.                   
import json
obj  = json.load(open("file.json"))

# Iterate through the objects in the JSON and pop (remove)                      
# the obj once we find it.                                                      
for i in xrange(len(obj)):
    if obj[i]["ename"] == "mark":
        obj.pop(i)
        break

# Output the updated file with pretty JSON                                      
open("updated-file.json", "w").write(
    json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)

The main point is that we find the object by iterating through the objects in the loaded list, and then pop the object off the list once we find it. If you need to remove more than one object in the list, then you should store the indices of the objects you want to remove, and then remove them all at once after you've reached the end of the for loop (you don't want to modify the list while you iterate through it).

2 of 5
12

The proper way to json is to deserialize it, modify the created objects, and then, if needed, serialize them back to json. To do so, use the json module. In short, use <deserialized object> = json.loads(<some json string>) for reading json and <json output> = json.dumps(<your object>) to create json strings. In your example this would be:

import json
o = json.loads("""[
    {
        "ename": "mark",
        "url": "Lennon.com"
    },
    {
        "ename": "egg",
        "url": "Lennon.com"
    }
]""")
# kick out the unwanted item from the list
o = filter(lambda x: x['ename']!="mark", o)
output_string = json.dumps(o)
🌐
Raspberry Pi Forums
forums.raspberrypi.com › board index › programming › python
Trying to remove some elements from JSON data - Raspberry Pi Forums
with requests.request('get', ... data = json.load(data_file) for element in data: element.pop('hours', None) with open('response.json', 'w') as data_file: data = json.dump(data, data_file) newData = response.json() #this line is from my script and modified it into ...
🌐
Zyte
zyte.com › home › blog › json parsing with python [practical guide]
JSON Parsing with Python [Practical Guide]
December 3, 2024 - The json module provides two methods, loads and load, that allow you to parse JSON strings and JSON files, respectively, to convert JSON into Python objects such as lists and dictionaries. Next is an example on how to convert JSON string to a Python object with the loads method.
🌐
Stack Overflow
stackoverflow.com › questions › 72951553 › why-does-in-my-code-json-pop-dont-work-in-python
Why does in my code json pop dont work? (In python) - Stack Overflow
I code a Python Discord Bot and it saves the channel id and the owner id! And if the ticket got closed it need to pop ticket! ... { "channel id 1": { "author": 256820568024, "claimed": null }, "channel id 2": { "author": 43251524366254, "claimed": null } but if i try to close the ticket! Its delete the complete tickets.json file!
Find elsewhere
🌐
GitHub
github.com › ddfs › python-json-doc
GitHub - ddfs/python-json-doc: Utility functions for JSON Document
doc = { 'a': { 'deep': { 'nested': { 'list': [1, 2, 3, {'dict': 'OK'}], 'string': 'string', 'hex': 0x010101 } }, }, 'list': [1, 2, 3] } # get print json_doc_get(doc, '/a/deep/nested/list/3/dict') >> OK # set print json_doc_set(doc, ...
Author: ddfs
🌐
W3Schools
w3schools.com › python › ref_list_pop.asp
Python List pop() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The pop() method removes the element at the specified position.
🌐
Programiz
programiz.com › python-programming › methods › dictionary › pop
Python Dictionary pop()
element = sales.pop('guava', 'banana') print('The popped element is:', element) print('The dictionary is:', sales)
🌐
GeeksforGeeks
geeksforgeeks.org › python-dictionary-pop-method
Python Dictionary pop() Method - GeeksforGeeks
May 9, 2025 - This view is dynamic, meaning it reflects any changes made to the dictionary (like adding or removing keys) after calling the method. Example:Pythond = {'A': 'Geeks', 'B': 'For', 'C': 'Ge ... The Python pop() method removes and returns the value ...
🌐
Stack Overflow
stackoverflow.com › questions › 69230641 › how-do-i-pop-the-list-after-reading-the-json-url
python - How do I pop the [List] after reading the JSON URL? - Stack Overflow
September 18, 2021 - import json import urllib.request url = "https://jsonplaceholder.typicode.com/posts" data = urllib.request.urlopen(url).read().decode() site_info =json.loads(data) for info in site_info: print("{}, {}, {}, {}".format( info["userId"], info["id"], info["title"], info["body"])) mylist= [{"userId":1},{"userId":2},{"userId":3},{"userId":4},{"userId":5}, {"userId":6},{"userId":7},{"userId":8},{"userId":9},{"userId":10}] for i in (5,0): print(i) if mylist[i]["userId"] == 5: mylist.pop(i) print (mylist)
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.7 documentation
object_hook (callable | None) – If set, a function that is called with the result of any JSON object literal decoded (a dict). The return value of this function will be used instead of the dict.
🌐
GeeksforGeeks
geeksforgeeks.org › python › update-json-key-name-in-python
Update JSON Key Name in Python - GeeksforGeeks
July 23, 2025 - In this example, below Python code utilizes the `json` library to update key names within a JSON object. It loads the original JSON string into a dictionary (`json_data`), performs key updates using `pop` and assignment, and then converts the ...
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.
🌐
Medium
medium.com › analytics-vidhya › python-dictionary-and-json-a-comprehensive-guide-ceed58a3e2ed
Python Dictionary and JSON — A Comprehensive Guide | by Kiprono Elijah | Analytics Vidhya | Medium
January 11, 2024 - Python dictionary is a a collection of key-value pairs. Dictionary is mutable(can be changed), unordered and can be indexed. JSON is a data format...
🌐
Geekflare
geekflare.com › home › development › how to parse json in python
How to Parse JSON in Python - Geekflare
July 31, 2023 - This is a tutorial on JSON in Python. You'll learn to parse and create JSON strings and work with JSON files with code examples.