【问题标题】:Sort dictionary by value property按值属性对字典进行排序
【发布时间】:2021-01-24 17:33:22
【问题描述】:

字典怎么办

class Foo:
    def __init__(self,value):
        self.property = value
        
dictionary = {"one":Foo(1),
              "two":Foo(2)}

Foo对象的self.property的值降序排列?

【问题讨论】:

  • 您想将它们分类打印吗?因为你不能对字典进行排序。您可以通过key 而不是索引来访问它们。我说的对吗?
  • check this post。 3.6+ 中的字典是插入顺序的

标签: python sorting dictionary


【解决方案1】:
sorted_dict = {k: v for k, v in sorted(dictionary.items(), key=lambda item: item[1].property)}

【讨论】:

    【解决方案2】:

    容易 - 不要。字典是一种数据结构,旨在允许键与其值之间的有效关联。因此,Python 使用了一种方便的排序方式。如果您需要排序的结果,则将所需的值选择到更合适的结构(可能是列表)中并对其进行排序。

    【讨论】:

      猜你喜欢
      • 2019-01-25
      • 2016-04-16
      • 1970-01-01
      • 2012-04-20
      • 2012-05-18
      • 1970-01-01
      • 2011-02-09
      相关资源
      最近更新 更多