<p>在排序操作期间,您需要将价格和名称保持在一起。这可以通过将它们组合在一个元组列表中(从价格开始)来实现,您可以对这些元组进行排序,然后将其分配回字典项:</p>
<pre><code>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]}
</code></pre>
<p><em>注意:我添加了一个“其他”产品,以清楚地表明产品名称不仅仅按字母顺序排序</em></p>
<p>另一种方法是编写两个helper函数来获取排序,并将排序从一个排序应用到相同大小的多个列表:</p>
<pre><code>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)
</code></pre>
<P><EM>BTW,如果您不致力于这个数据结构,您应该真正考虑将其更改为元组列表或字典列表,该列表将每个产品的名称和价格保持在一起,而不是依赖于名称和价格在相同的索引上。如果您想使用这种模型,还可以查看pandas/dataframes</em></p>