【问题标题】:Sort by key of dictionary inside a dictionary in Python在Python中的字典中按字典键排序
【发布时间】:2011-01-25 18:21:39
【问题描述】:

如何按照“remaining_pcs”或“discount_ratio”的值对以下字典进行排序?

promotion_items = {
    'one': {'remaining_pcs': 100, 'discount_ratio': 10},
    'two': {'remaining_pcs': 200, 'discount_ratio': 20},
}

编辑

我的意思是获取上述字典的排序列表,而不是对字典本身进行排序。

【问题讨论】:

    标签: python dictionary sorting


    【解决方案1】:

    请看To sort a dictionary:

    字典无法排序——a 映射没有顺序! ——那么,当 你觉得有必要整理一个,你没有 怀疑要对其键进行排序(在 单独的列表)。

    【讨论】:

      【解决方案2】:

      如果 'remaining_pcs''discount_ratio' 是嵌套字典中的唯一键,则:

      result = sorted(promotion_items.iteritems(), key=lambda pair: pair[1].items())
      

      如果还有其他键,那么:

      def item_value(pair):
          return pair[1]['remaining_pcs'], pair[1]['discount_ratio']
      result = sorted(promotion_items.iteritems(), key=item_value)
      

      【讨论】:

        【解决方案3】:

        您只能将字典的(或项目或值)排序到一个单独的列表中(正如我多年前在@Andrew 引用的食谱中所写的那样)。例如,根据您声明的标准对键进行排序:

        promotion_items = {
            'one': {'remaining_pcs': 100, 'discount_ratio': 10},
            'two': {'remaining_pcs': 200, 'discount_ratio': 20},
        }
        def bypcs(k):
          return promotion_items[k]['remaining_pcs']
        byrempcs = sorted(promotion_items, key=bypcs)
        def bydra(k):
          return promotion_items[k]['discount_ratio']
        bydiscra = sorted(promotion_items, key=bydra)
        

        【讨论】:

        • 第二个def bypcs 我想你的意思是def bydra
        • @unutbu,对,我看到 Mike Graham 已经编辑了我的 A 来解决这个问题(两个都发送!)。
        猜你喜欢
        • 2015-11-12
        • 1970-01-01
        • 2021-03-28
        • 2021-11-27
        • 2011-06-17
        • 2019-08-12
        • 2019-04-21
        • 2013-05-18
        相关资源
        最近更新 更多