需要帮助在价格属性的python 3中对字典的特定键进行排序

时间:2018-03-13 14:21:13

标签: sorting dictionary python-3.6

您好我正在尝试排序字典列表。我的目标是在价格基础上对字典进行排序。我正在使用python 3.6。 我的初始字典是

basketContent = {'id': '1940', 'price': 10.8}, {'id': '1234', 'price': 130.5}

我必须对它进行排序。它必须将最终字典填充为{'id': '1234', 'price': 130.5}, {'id': '1940', 'price': 10.8}

我正在使用以下功能

def usort(_a, _b):
    if _a['price'] > _b['price']:
        return -1
    elif _b['price'] > _a['price']:
        return 1
    return 0
sorted(basketContent, usort)

2 个答案:

答案 0 :(得分:0)

传递一个带字典的lambda,并将price值返回到sorted中的key函数。键函数只需要一个参数,并且应该返回该参数的一些参数,根据它对序列进行排序。

答案 1 :(得分:0)

发现此搜索内容另存为... 好吧,您的basketContent是一个元组..它不是可排序的。 实际上,您的basketContent必须是字典列表。 然后:

import operator
basketContent = [ {'id': '1940', 'price': 10.8}, {'id': '1234', 'price': 130.5} ]
basketContent.sort(key=operator.itemgetter('price'), reverse =True)