0

I'm trying to extract the value associated with lowPrice in a list of dictionaries using a list comprehension.

I'm having an issue (I think) because the "lowPrice" key isn't found in the dictionary contained in the first list.

Minimum Reproducible Example

offers = [
    {
        "@type": "AggregateOffer",
        "priceCurrency": "GBP",
        "name": "Mini Sized Basketball",
        "sku": "GHSNC52",
        "mpn": "GHSNC52",
        "url": "https://www.basketballsrus.com/mini-sized-basket-ball",
        "itemCondition": "https://schema.org/NewCondition",
        "availability": "https://schema.org/LimitedAvailability",
    },
    {
        "@type": "AggregateOffer",
        "highPrice": "20.24",
        "lowPrice": "20.24",
        "priceCurrency": "GBP",
        "name": "Full Sized Basket Ball",
        "sku": "GHSNC75",
        "mpn": "GHSNC75",
        "url": "https://www.basketballsrus.com/full-sized-basket-ball",
        "itemCondition": "https://schema.org/NewCondition",
        "availability": "https://schema.org/InStock",
    },
]

My code:

lowPrice = [d['highPrice'] for d in offers]

this produces a KeyError.

Desired Output 20.24

How can I fix the KeyError? Or alternatively work around it?

emely_pi
  • 517
  • 5
  • 23
Lee Roy
  • 297
  • 1
  • 11
  • 1
    use dict.get with a default: `lowPrice = [d.get('highPrice', None) for d in offers]` that will not throw an error when the key is missing from the dict. – Vinzent May 31 '22 at 11:38
  • Does this answer your question? [How to properly ignore exceptions](https://stackoverflow.com/questions/730764/how-to-properly-ignore-exceptions) – Joooeey May 31 '22 at 11:39

1 Answers1

1
lowPrice = [d['lowPrice'] for d in offers if 'lowPrice' in d.keys()]

print(lowPrice)
Olasimbo
  • 965
  • 6
  • 14
  • This is relatively slow because the lookup will happen twice. – Vinzent May 31 '22 at 11:41
  • Are we tackling speed or getting it work? – Olasimbo May 31 '22 at 11:42
  • `key in d` is fast ... that is the single thing that `dict`s are good at: O(1) value lookup. Btw. `'lowPrice' in d` should be sufficient. – Patrick Artner May 31 '22 at 11:44
  • @PatrickArtner you end up doing the lookup twice when the key is in the dict.. thats all I'm saying.. you could do `lowPrice = [x for d in offers if (x := d.get('highPrice', None)) is not None]` in newer python versions. – Vinzent May 31 '22 at 11:47