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
🌐
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 Bootcamp Python Training ... car = { "brand": "Ford", "model": "Mustang", "year": 1964 } car.pop("model") print(car) Try it Yourself »
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'}}
Discussions

python - How do I extract the values of the first element of a JSON file? - Stack Overflow
Ok so I have this JSON file here: https://api.tvmaze.com/shows/25376/episodes, which is basically just a list, and each item in the list is a dictionary. I want to get all the values of the first e... More on stackoverflow.com
🌐 stackoverflow.com
python - Read the first Json Element in a Pythonscript - Stack Overflow
Consider an API that gives a JSON response, which will have the same order for every request, even if it's meaningless. e.g. an API that gives research paper links/metrics on a subject, like covid-19, we could see if the first paper was different, implying a new paper was published since the ... More on stackoverflow.com
🌐 stackoverflow.com
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
python - How do I pop the [List] after reading the JSON URL? - Stack Overflow
import json import urllib.request ... mylist.pop(i) print (mylist) ... Usually, the best way to do this is to create a new list, and copy over the elements you DON'T want to delete. ... No, replace the first list. See my answer below. ... Have you looked at my answer? That code works. ... I'm not sure what you're doing with my code, since you haven't posted any updates, but it works perfectly well. Here I am processing the received JSON, and you can ... More on stackoverflow.com
🌐 stackoverflow.com
September 18, 2021
🌐
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
You need to read in the existing JSON, delete a key from it or whatever other modifications you want to make, and only then write it out again using json.dumps. ... can you share the code which defines the variable data? at minimum you should ...
🌐
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:
🌐
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', 'api.openweathermap.org/data/2.5/weather', timeout=30, headers=headers) as response: #this line is from my script with open('response.json', 'r') as data_file: #this line is from StackOverflow 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 this:
🌐
freeCodeCamp
freecodecamp.org › news › python-pop-how-to-pop-from-a-list-or-an-array-in-python
Python .pop() – How to Pop from a List or an Array in Python
March 1, 2022 - So, to remove the first item in a list, you specify an index of 0 as the parameter to the pop() method. And remember, pop() returns the item that has been removed. This enables you to store it in a variable, like you saw in the previous section.
🌐
W3Schools
w3schools.com › python › ref_list_pop.asp
Python List pop() Method
Python Examples Python Compiler ... Plan Python Interview Q&A Python Bootcamp Python Training ... The pop() method removes the element at the specified position....
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python-dictionary-pop-method
Python Dictionary pop() Method - GeeksforGeeks
May 9, 2025 - Explanation: while loop repeatedly removes and prints the first key-value pair from the dictionary using pop() until the dictionary is empty. ... Python dictionary methods is collection of Python functions that operates on Dictionary.Python ...
🌐
Stack Overflow
stackoverflow.com › questions › 67517671 › read-the-first-json-element-in-a-pythonscript
python - Read the first Json Element in a Pythonscript - Stack Overflow
i need the first json object´s name (here in this examole its "object") as a String. The Json looks like this: {'object':{'a': ['123', '234', '345'], 'b' : '1234'}} but the objects name switches randomly with the user input. So I need to read the first element of the Json file like list[0] with lists. python ·
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)
🌐
Programiz
programiz.com › python-programming › methods › dictionary › pop
Python Dictionary pop()
element = marks.pop('Chemistry') print('Popped Marks:', element) # Output: Popped Marks: 72
🌐
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 ... mylist.pop(i) print (mylist) ... Usually, the best way to do this is to create a new list, and copy over the elements you DON'T want to delete. ... No, replace the first list. See my answer below. ... Have you looked at my answer? That code works. ... I'm not sure what you're doing with my code, since you haven't posted any updates, but it works perfectly well. Here I am processing the received JSON, and you can ...
🌐
Reddit
reddit.com › r/learnpython › removing the first element in a file list
r/learnpython on Reddit: Removing the first element in a file list
November 6, 2021 -

I have a file with a list inside and I want to remove the first option of that list whenever I use the command. When you open the file, it'll have something like ['a', 'b', 'c']. However I want to remove the first element of this list, in this case 'a' and I know that to print the first element I either can do print(list(file[0])) or print(a[1:]). But since I want to remove the first element in the list of the file I am absolutely clueless on what to do. Do I have to use a .replace, .remove or something else in order to remove the first option every time I run the command?

🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-remove-first-element-from-array-in-pythonexample.html
How to Remove First Element from List in Python? - ItSolutionstuff.com
October 30, 2023 - This article will give you simple example of python list remove first element. I would like to share with you python list remove one element. you will learn python list remove first n elements. In this example, I will give you two examples. one using "del" in python and another using "pop" function ...
Top answer
1 of 3
3

First question

However, whenever there's more than two elements and I enter anything higher than two, it doesn't delete anything. Even worse, when I enter the number one, it deletes everything but the zero index(whenever the array has more than two elements in it).

Inside delete_data() you have two lines reading i = + 1, which just assignes +1 (i.e., 1) to i. Thus, you're never increasing your index. You probably meant to write either i = i+1 or i += 1.

def delete_data():    # Deletes an element from the array
    view_data()
    new_data = []
    with open(filename, "r") as f:
        data = json.load(f)
        data_length = len(data) - 1
    print("Which index number would you like to delete?")
    delete_option = input(f"Select a number 0-{data_length}: ")
    i = 0
    for entry in data:
        if i == int(delete_option):
            i += 1  # <-- here
        else:
            new_data.append(entry)
            i += 1  # <-- and here

    with open(filename, "w") as f:
        json.dump(new_data, f, indent=4)

Second question: further improvements

Is there a better way to implement that in my Python script?

First, you can get rid of manually increasing i by using the builtin enumerate generator. Second, you could make your functions reusable by giving them parameters - where does the filename in your code example come from?

# view_data() should probably receive `filename` as a parameter
def view_data(filename: str):   # Prints JSON Array to screen
    with open(filename, "r") as f:
        data = json.load(f)
        # iterate over i and data simultaneously
        # alternatively, you could just remove i
        for i, item in enumerate(data):
            name = item["name"]
            chromebook = item["chromebook"]
            check_out = item["time&date"]
            print(f"Index Number: {i}")
            print(f"Name : {name}")
            print(f"Chromebook : {chromebook}")
            print(f"Time Of Checkout: {check_out} ")
            print("\n\n")
            # not needed anymore: i = i + 1

# view_data() should probably receive `filename` as a parameter
def delete_data(filename: str):    # Deletes an element from the array
    view_data()
    new_data = []
    with open(filename, "r") as f:
        data = json.load(f)
        data_length = len(data) - 1
    print("Which index number would you like to delete?")
    delete_option = input(f"Select a number 0-{data_length}: ")
    # iterate over i and data simultaneously
    for i, entry in enumerate(data):
        if i != int(delete_option):
            new_data.append(entry)

    with open(filename, "w") as f:
        json.dump(new_data, f, indent=4)

Furthermore, you could replace that for-loop by a list comprehension, which some may deem more "pythonic":

new_data = [entry for i, entry in enumerate(data) if i != int(delete_option)]
2 of 3
3

There are easier ways to delete an element by index from a Python list.

Given li = ["a", "b", "c"], you can delete element 1 ("b") by index in (at least) the following ways:

li.pop(1) # pop takes an index (defaults to last) and removes and returns the element at that index

del li[1] # the del keyword will also remove an element from a list

So, here's some updated code:

def view_data():   # Prints JSON Array to screen
    with open(filename, "r") as f:
        data = json.load(f)
        i = 0
        for item in data:
            name = item["name"]
            chromebook = item["chromebook"]
            check_out = item["time&date"]
            print(f"Index Number: {i}")
            print(f"Name : {name}")
            print(f"Chromebook : {chromebook}")
            print(f"Time Of Checkout: {check_out} ")
            print("\n\n")
            i = i + 1

def delete_data():    # Deletes an element from the array
    view_data()
    with open(filename, "r") as f:
        data = json.load(f)
        data_length = len(data) - 1
    print("Which index number would you like to delete?")
    delete_option = input(f"Select a number 0-{data_length}: ")
    del data[int(delete_option)] # or data.pop(int(delete_option))

    with open(filename, "w") as f:
        json.dump(data, f, indent=4)
🌐
Mimo
mimo.org › glossary › python › pop()
Python Pop Method: Essential Data Manipulation techniques
In Python, pop() is a list method that removes and returns an element of a list. With an argument, pop() removes and returns the item at the specified index (starting from 0).
🌐
DataCamp
datacamp.com › tutorial › python-pop
How to Use the Python pop() Method | DataCamp
July 31, 2024 - When we use the pop() method to remove the first or any other element, it works in O(n) time because it involves removing an element and shifting the other elements to a new index order. Check out our Analyzing Complexity of Code through Python tutorial to learn more about time complexity in Python.