我在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实现这一点?
事先谢谢你
发布于 2021-03-03 09:14:26
在排序操作期间,您需要将价格和名称放在一起。这可以通过将它们组合到一个元组列表(从价格开始)来实现,然后将它们排序并分配回字典条目:
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)顺便说一句,如果您没有致力于这个数据结构,那么您应该考虑将其更改为元组列表,或者将每个产品的名称和价格放在一起的字典列表,而不是依赖名称和价格处于相同的索引。如果你想使用这种模型的话,你也可以看看熊猫/数据。
发布于 2021-03-03 09:19:40
下面是一个使用价格作为列表来查找排序的版本。
initial_price = dictionaryofproduct['price'] # backup
dictionaryofsortedproduct = {key: [v for _, v in sorted(zip(initial_price, value))] for key, value in dictionaryofproduct.items()}其思想是在键/值上迭代,并使用初始价目表压缩值。
发布于 2021-03-03 09:30:21
您可以使用此示例来实现以下目标:
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)通过压缩两个键的值,使单个名称对应于单个价格。
https://stackoverflow.com/questions/66453810
复制相似问题