【问题标题】:Python sort list of dictionary by float valuesPython按浮点值排序字典列表
【发布时间】:2020-09-08 09:20:12
【问题描述】:

以下是我的清单

List_data = [{'cases_covers': 0.1625}, {'headphone': 0.1988}, {'laptop': 0.2271}, {'mobile': 0.2501}, {'perfume': 0.4981}, {'shoe': 0.1896}, {'sunglass': 0.1693}]

最终答案应该是这样的:

[{'perfume': 0.4981}, {'mobile': 0.2501}, {'laptop': 0.2271}, {'headphone': 0.1988},{'shoe': 0.1896}, {'sunglass': 0.1693},{'cases_covers': 0.1625}]

我希望它们根据键的值按降序排序

【问题讨论】:

标签: python-3.x list sorting dictionary


【解决方案1】:

您可以通过d.values() 获取字典d 列表。由于您的字典每个只有一个条目,因此这些列表将是单例的。您可以使用这些单例列表对 List_data 进行排序,方法是向 sort 函数提供关键字参数。

请注意,在您的示例中,"perfume", "mobile", "laptop"keys0.4981, 0.2501values,根据 python 中的字典标准词汇表。 p>

List_data = [{'cases_covers': 0.1625}, {'headphone': 0.1988}, {'laptop': 0.2271}, {'mobile': 0.2501}, {'perfume': 0.4981}, {'shoe': 0.1896}, {'sunglass': 0.1693}]
List_data.sort(key=lambda d: list(d.values()), reverse=True)
print(List_data)

输出:

[{'perfume': 0.4981}, {'mobile': 0.2501}, {'laptop': 0.2271}, {'headphone': 0.1988}, {'shoe': 0.1896}, {'sunglass': 0.1693}, {'cases_covers': 0.1625}]

重要说明

上一段代码是按字面意思回答您的问题,但并不知道您尝试对该字典列表进行排序的上下文。

我的印象是您对列表和字典的使用不是最佳的。当然,在不了解上下文的情况下,我只是猜测。但也许只使用一本字典会更好地满足您的需求:

dictionary_data = {'cases_covers': 0.1625, 'headphone': 0.1988, 'laptop': 0.2271, 'mobile': 0.2501, 'perfume': 0.4981, 'shoe': 0.1896, 'sunglass': 0.1693}
list_data = sorted(dictionary_data.items(), key=lambda it: it[1], reverse=True)
print(list_data)

输出:

[('perfume', 0.4981), ('mobile', 0.2501), ('laptop', 0.2271), ('headphone', 0.1988), ('shoe', 0.1896), ('sunglass', 0.1693), ('cases_covers', 0.1625)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    相关资源
    最近更新 更多