Python使用另一个列表对字典列表进行排序

2024-06-17 13:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的数据

pricing = [
    {
      "link": "https://www.kohls.com/product/prd-3751773/laura-geller-iconic-baked-sculpting-lipstick.jsp?skuid=75792684",
      "price": "21",
      "stock": true,
      "title": "Laura Geller Iconic Baked Sculpting Lipstick, Red Overfl",
      "seller": "Kohl's"
    },
    {
      "link": "https://www.macys.com/shop/product/laura-geller-beauty-iconic-baked-sculpting-lipstick-cream?ID=5713197&PartnerID=LINKSHARE&cm_mmc=LINKSHARE-_-4-_-41-_-MP441",
      "price": "21.00",
      "stock": true,
      "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
      "seller": "Macy's"
    },
            {
      "link": "https://www.macys.com/shop/product/laura-geller-beauty-iconic-baked-sculpting-lipstick-cream?ID=5713197&PartnerID=LINKSHARE&cm_mmc=LINKSHARE-_-4-_-41-_-MP441",
      "price": "21.00",
      "stock": true,
      "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
      "seller": "Wal-Mart.com"
    }
  ]

下面是我正在编写的代码,请按照列表对它们进行排序

retailers = ["Amazon", "Wal-Mart.com", "Target", "CVS",  "Walgreens","Macy’s", "Nordstrom", "MassGenie", "Kohl's", "Kmart"]
data = sorted(pricing, key=lambda x: retailers.index(x['seller']))

错误:

ValueError at /api/product/
"Macy's" is not in list

在这里,我试图根据列表零售商按卖家键对数据进行排序,但是,在对数据排序时,我遇到了键错误。请看一下我哪里出错了

我期待的结果是:

pricing = [
    {
      "link": "https://www.macys.com/shop/product/laura-geller-beauty-iconic-baked-sculpting-lipstick-cream?ID=5713197&PartnerID=LINKSHARE&cm_mmc=LINKSHARE-_-4-_-41-_-MP441",
      "price": "21.00",
      "stock": true,
      "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
      "seller": "Wal-Mart.com"
    },
    {
      "link": "https://www.macys.com/shop/product/laura-geller-beauty-iconic-baked-sculpting-lipstick-cream?ID=5713197&PartnerID=LINKSHARE&cm_mmc=LINKSHARE-_-4-_-41-_-MP441",
      "price": "21.00",
      "stock": true,
      "title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
      "seller": "Macy's"
    },
    {
      "link": "https://www.kohls.com/product/prd-3751773/laura-geller-iconic-baked-sculpting-lipstick.jsp?skuid=75792684",
      "price": "21",
      "stock": true,
      "title": "Laura Geller Iconic Baked Sculpting Lipstick, Red Overfl",
      "seller": "Kohl's"
    }
  ]

请看一看


Tags: httpscomwwwstocklinkproductbakedprice
3条回答

您当前的retailers列表如下所示:

  retailers = ["Amazon", "Wal-Mart.com", "Target", "CVS",  "Walgreens","Macy’s", "Nordstrom", "MassGenie", "Kohl's", "Kmart"]

换成

  retailers = ["Amazon", "Wal-Mart.com", "Target", "CVS",  "Walgreens","Macy's", "Nordstrom", "MassGenie", "Kohl's", "Kmart"]

我所做的就是把改成'

顺便说一句,Kohl's看起来是正确的

你的代码是正确的。问题是"Macy’s""Macy's"不同(注意不同的撇号字符)

代码中有两个错误

  1. macy’sretailers列表中而不是macy's
  2. true在{}列表中而不是True(在python中,布尔值以大写字母开头)

相关问题 更多 >