0

I have two corresponding lists:

  1. One is a list of items
  2. The other is a list of labels for those items

I want to write a function that check if each item in the 1st list is a JSON object. If it is, it should remain in the list but if not, then it and its corresponding label should be deleted.

I wrote the following script to do this:

import json 
def check_json (list_of_items, list_of_labels):
    for item in list_of items:
        try:
            json.loads(item)
            break
        except ValueError:
            index_item = list_of_items.index(item)
            list_of_labels.remove(index_item)
            list_of_items.remove(index_item)

However, it does not remove items that are not JSON objects.

2 Answers 2

1

Don't try to modify the list you are iterating over; it breaks the iterator. Instead, build and return new lists.

import json 
def check_json (list_of_items, list_of_labels):
    new_items = []
    new_labels = []
    for item, label in zip(list_of items, list_of_labels):
        try:
            json.loads(item)
        except ValueError:
            continue
        new_items.append(item)
        new_labels.append(label)
    return new_items, new_labels

If you insist modifying the original arguments:

def check_json (list_of_items, list_of_labels):
    new_items = []
    new_labels = []
    for item, label in zip(list_of items, list_of_labels):
        try:
            json.loads(item)
        except ValueError:
            continue
        new_items.append(item)
        new_labels.append(label)
    list_of_items[:] = new_items
    list_of_labels[:] = new_labels

but note that this isn't really any more efficient; it just provides a different interface.

Sign up to request clarification or add additional context in comments.

Comments

0

You can create a list comprehension and unzip it:

def is_json(item):
    try:
        json.loads(item)
        return True
    except ValueError:
        return False


temp = [(item, label) for item, label in zip(items, labels) if is_json(item)]
items, labels = zip(*temp)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.