0

I have a json file with objects with the same ID. I have a results list inside each. How to remove the entire object if results == [] ? I have a And I have a UnboundLocalError: local variable 'item' referenced before assignment error.

JSON input:

[{
    "objectID": 10745,
    "results": [
    {
        "model": "AUDI - TT QUATTRO",
        "price_str": "4 800 €"
        }]
    },
 {
    "objectID": 10745,
    "results": []
    }
]

My code:

for item in data:
    objectId = item["objectID"]
    results = item["results"]

    def removeDuplicate():
        if not results:
            del item
    removeDuplicate()

The expected output:

[{
    "objectID": 10745,
    "results": [
    {
        "model": "AUDI - TT QUATTRO",
        "price_str": "4 800 €"
         }]
    }
]
wjandrea
  • 28,235
  • 9
  • 60
  • 81
lf_celine
  • 653
  • 7
  • 19
  • Read [short-description-of-the-scoping-rules](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) to get the error message. – Patrick Artner Apr 30 '20 at 15:20

2 Answers2

2

Deleting items from a list while iterating the same list is likely to cause trouble. Try constructing a new list instead with filtering logic to remove the unwanted items:

new_data = [item for item in data if item['results']]
AbbeGijly
  • 1,191
  • 1
  • 4
  • 5
0

Filter on the list of dictionaries based on the dicts value for "results":

data = [{
    "objectID": 10745,
    "results": [
    {
        "model": "AUDI - TT QUATTRO",
        "price_str": "4 800 EUR"
    }]
    },
    {
    "objectID": 10745,
    "results": []
    }
]

cleared = [i for i in data if i.get("results")] 

print(cleared)

Output:

[{'objectID': 10745, 
  'results': [{'model': 'AUDI - TT QUATTRO', 'price_str': '4 800 EUR'}]}]

If no "results"in the dict .get() will return None - if present and empty it is falsy as well (None and empty lists are) and it will not land inside cleared.

Regarding your error a good read of short-description-of-the-scoping-rules should help you get the error message: your item is not declared inside your functions scope and python does not allow you to use the item from the for loop.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69