【问题标题】:how to sort dictionary that has list inside it?如何对里面有列表的字典进行排序?
【发布时间】:2021-03-03 09:03:24
【问题描述】:

我在 python 中有以下字典:

dictionaryofproduct={
    "name":["Magnetic Adsorption Aluminum Bumper Case For Samsung Note 8","ESET Nod32 Antivirus"],
    "price":[1200,212]
}

我想按升序顺序的价格列表对字典进行排序,如下所示:

dictionaryofproduct={
    "name":["ESET Nod32 Antivirus","Magnetic Adsorption Aluminum Bumper Case For Samsung Note 8"],
    "price":[212,1200]
}

如何使用 python 实现这一点?

提前谢谢你

【问题讨论】:

    标签: python list sorting dictionary


    【解决方案1】:

    您需要在排序操作期间将价格和名称放在一起。这可以通过将它们组合在您排序的元组列表中(从价格开始)然后分配回字典项目来实现:

    dictionaryofproduct={
        "name":["Magnetic Adsorption Aluminum Bumper Case For Samsung Note 8","ESET Nod32 Antivirus","Other"],
        "price":[1200,212,500]
    }
    
    prices,names = zip(*sorted(zip(dictionaryofproduct["price"],dictionaryofproduct["name"])))
    dictionaryofproduct["price"] = list(prices)
    dictionaryofproduct["name"]  = list(names)    
    
    print(dictionaryofproduct)
    
    {'name': ['ESET Nod32 Antivirus', 'Other', 'Magnetic Adsorption Aluminum Bumper Case For Samsung Note 8'],
     'price': [212, 500, 1200]}
    

    注意:我添加了一个“其他”产品以清楚地表明产品名称不只是按字母顺序排序

    另一种方法是编写两个辅助函数来获取排序并将排序应用于多个相同大小的列表:

    def getSortOrder(L,key=lambda v:v): 
        return sorted(range(len(L)),key=lambda i:key(L[i]))
    def applySortOrder(L,order): L[:] = [L[i] for i in order]
                                                    
    orderByPrice = getSortOrder(dictionaryofproduct["price"])
    applySortOrder(dictionaryofproduct["price"], orderByPrice)
    applySortOrder(dictionaryofproduct["name"],  orderByPrice)
    

    顺便说一句,如果您不致力于此数据结构,您应该真正考虑将其更改为元组列表或字典列表,将每个产品的名称和价格放在一起,而不是依赖名称和价格处于相同的索引。如果您想使用这种模型,也可以查看 pandas/dataframes。

    【讨论】:

      【解决方案2】:

      这是一个使用价格作为列表来查找排序的版本。

      initial_price = dictionaryofproduct['price'] # backup
      dictionaryofsortedproduct = {key: [v for _, v in sorted(zip(initial_price, value))] for key, value in dictionaryofproduct.items()}
      

      这个想法是对键/值进行迭代,然后将值与初始价目表一起压缩。

      【讨论】:

        【解决方案3】:

        您可以使用此示例来实现:

        dictionaryofproduct={
            "name":["Magnetic Adsorption Aluminum Bumper Case For Samsung Note 8","ESET Nod32 Antivirus"],
            "price":[1200,212]
        }
        
        pair = zip(dictionaryofproduct.get("name"), dictionaryofproduct.get("price"))
        dictionaryofproduct["name"] = [item[0] for item in sorted(pair, key=lambda x: x[1])]
        dictionaryofproduct["price"].sort()
        print(dictionaryofproduct)
        
        1. 通过压缩来聚合/打包这两个键的值,以便一个名称对应一个价格。
        2. 使用 sorted() 函数根据价格(即第二个参数 (x[1]))对压缩后的值进行排序并获取排序后的名称。
        3. 最后也对原始价格进行排序。

        【讨论】:

          【解决方案4】:

          您似乎有一个产品名称列表和一个价格列表,它们是 应该根据列表中的位置进行匹配。这个设计非常 容易出错,而且很难找到产品的价格。

          我会首先为您的数据建议一种不同的设计,其中包含一个列表(不是 产品的字典),以及具有属性的每个产品的字典 您感兴趣的(名称、价格):

          listofproduct = [
              {
                  "name": "Magnetic Adsorption Aluminum Bumper Case For Samsung Note 8",
                  "price": 1200,
              },
              {
                  "name": "ESET Nod32 Antivirus",
                  "price": 212,
              },
              {
                  "name": "Other",
                  "price": 500,
              },
          ]
          

          现在很容易按升序排序:

          sortedlist = sorted(listofproduct, key=lambda x: x['price'])
          

          key 参数是一个函数,将应用于 列表(由xvariable 表示)返回用作排序的值 键,在这种情况下是产品的价格。

          【讨论】:

            猜你喜欢
            • 2021-09-07
            • 2015-07-07
            • 2021-01-11
            • 2015-05-29
            • 1970-01-01
            • 2010-09-09
            • 2018-09-27
            相关资源
            最近更新 更多