lf_celine
lf_celine

Reputation: 673

Check if key value is the same in a dict in python

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'}]}]

Upvotes: 1

Views: 62

Answers (3)

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

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': []
}]

Upvotes: 2

Jab
Jab

Reputation: 27495

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)]

Upvotes: 1

Moosa Saadat
Moosa Saadat

Reputation: 1167

You need to adjust your condition as:

new_data = [item for item in data if item['results'] and objectId != item["objectID"]]

Upvotes: 1

Related Questions