delete a Item from Json File

Question:

I have a list of JSON file. I would like to remove a certain id. like I want to remove 3rd id and print get the json without this.
my json file:

data = [
          {
            "id": 1,
            "name": "John Smith",
            "email": "[email protected]"
          },
          {
            "id": 2,
            "name": "Jane Smith",
            "email": "[email protected]"
          },
          {
            "id": 3,
            "name": "Bob Johnson",
            "email": "[email protected]"
          }
        ]

The output I like

data = [
          {
            "id": 1,
            "name": "John Smith",
            "email": "[email protected]"
          },
          {
            "id": 2,
            "name": "Jane Smith",
            "email": "[email protected]"
          }
        ]

I wrote this data = [item for item in data if item["id"] != 3] but I want a easy way to do it and I want to do it using index.

Asked By: Earth is Beautiful

||

Answers:

For this can use del operator to remove a certain id by index:

del data[2]
Answered By: Shounak Das

You have a list of dictionaries. Each dictionary has a key – ‘id’. You want to remove a dictionary from the list where the ‘id’ matches some value.

Here’s a robust approach that makes no assumptions about the order of the dictionaries in the list.

data = [
    {
        "id": 1,
        "name": "John Smith",
        "email": "[email protected]"
    },
    {
        "id": 2,
        "name": "Jane Smith",
        "email": "[email protected]"
    },
    {
        "id": 3,
        "name": "Bob Johnson",
        "email": "[email protected]"
    }
]


def get_index(data, _id):
    for i, d in enumerate(data):
        if d.get('id') == _id:
            return i
    raise ValueError


del data[get_index(data, 3)]

print(data)

Of course, reconstructing the list is a superior solution but OP has specifically stated that she wants to remove by index

Answered By: Fred
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.