如何对包含列表的词典进行排序?

2024-04-28 11:31:46 发布

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

我有以下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实现这一点?

先谢谢你


Tags: namefor字典pricenotecasebumpersamsung
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. 最后,对原始价格进行排序

这里有一个版本使用价格作为列表来查找排序

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

其思想是迭代键/值,并使用初始价目表压缩值

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

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

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

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

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)

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

相关问题 更多 >