1

I asked how to remove an object when a list inside it was empty in this question (Remove object if empty list inside it in Python). The problem is that I'd like to do this only when the objectId value is the same. I have others objects with different ids and I don't want to touch it.

Input:

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

]

My code:

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

        def removeDuplicate():
            #if objectid are the same
            new_data = [item for item in data if item['results']]
            data[:] = new_data
        removeDuplicate()

Expected output:

    [{'objectID': 10745, 
  'results': [{'model': 'AUDI - TT QUATTRO', 'price_str': '4 800 EUR'}]}, {'objectID': 10746, 
  'results': [{'model': 'Porsche 911', 'price_str': '48 000 EUR'}]}]
lf_celine
  • 653
  • 7
  • 19

3 Answers3

2

Although maybe not fast,but short.

data = [{
        "objectID": 10745,
        "results": [{
            "model": "AUDI - TT QUATTRO",
            "price_str": "4 800 EUR"
        }]
    },
    {
        "objectID": 10745,
        "results": []
    },
    {
        "objectID": 10746,
        "results": [{
            "model": "Porsche 911",
            "price_str": "48 000 EUR"
        }]
    },
    { # add a test example
        "objectID": 10747,
        "results": []
    }
]
r = [d for i,d in enumerate(data) if d['objectID'] not in set(map(lambda x:x['objectID'],data[:i])) or d['results']]
print(r)

Result:

[{
    'objectID': 10745,
    'results': [{
        'model': 'AUDI - TT QUATTRO',
        'price_str': '4 800 EUR'
    }]
}, {
    'objectID': 10746,
    'results': [{
        'model': 'Porsche 911',
        'price_str': '48 000 EUR'
    }]
}, {
    'objectID': 10747,
    'results': []
}]
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
1

You need to adjust your condition as:

new_data = [item for item in data if item['results'] and objectId != item["objectID"]]
Moosa Saadat
  • 1,159
  • 1
  • 8
  • 20
  • I I do this I only keep object with one `objectId` only no ? I want to target objects with the same id and then remove the ones with a empty `results` list – lf_celine Apr 30 '20 at 16:09
1

You can use itertools.groupby but you will need to sort the data. I'd use operator.itemgetter for the key.

from itertools import groupby
from operator import itemgetter

data = [...]

osort = itemgetter('objectID')
sorted_data = sorted(data, key=osort)

output = [next(o for o in g if o['results']) for _, g in groupby(sorted_data, osort)]
Jab
  • 26,853
  • 21
  • 75
  • 114