在迭代列表中提取值的列表时,如何修复发生的键盘?

发布于 2025-02-03 03:31:01 字数 1141 浏览 2 评论 0原文

我正在尝试使用列表理解的字典列表中提取与低价相关的值。

我有一个问题(我认为),因为“ lowprice”键在第一个列表中包含的字典中找不到。

最小可重复的示例

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",
    },
]

我的代码:

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

这会产生一个键盘。

所需的输出 20.24

我该如何修复键盘?还是围绕它来工作?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无声无音无过去 2025-02-10 03:31:01
lowPrice = [d['lowPrice'] for d in offers if 'lowPrice' in d.keys()]

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

print(lowPrice)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文