【问题标题】:Sort Multidimensional Dictionary by value and return newly sorted dictionary in Python按值排序多维字典并在Python中返回新排序的字典
【发布时间】:2017-12-17 05:37:03
【问题描述】:

以下是我拥有的示例字典。

    my_dict = {  
       '003':{  
          'class':'13',
          'marks':'90',
          'name':'CCC',
          'date_accessed':'2017-07-12 17:43:24'
       },
       '002':{  
          'marks':'90',
          'class':'10',
          'name':'BBB',
          'date_accessed':'2017-07-12 17:43:24'
       },
       '001':{  
          'marks':'80',
          'class':'9',
          'name':'AAA',
          'date_accessed':'2017-07-12 17:43:24'
       },
       '005':{  
          'date_accessed':'2017-07-12 17:43:42',
          'marks':'999',
          'name':'EEE',
          'class':'99'
       },
       '004':{  
          'class':'50',
          'marks':'100',
          'name':'DDD',
          'date_accessed':'2017-07-12 17:43:24'
       }
    }

现在我想按marks排序,所以结果字典会是这样的

    my_dict = { 
       '005':{  
          'date_accessed':'2017-07-12 17:43:42',
          'marks':'999',
          'name':'EEE',
          'class':'99'
       }, 
       '004':{  
          'class':'50',
          'marks':'100',
          'name':'DDD',
          'date_accessed':'2017-07-12 17:43:24'
       }
       '003':{  
          'class':'13',
          'marks':'90',
          'name':'CCC',
          'date_accessed':'2017-07-12 17:43:24'
       },
       '002':{  
          'marks':'90',
          'class':'10',
          'name':'BBB',
          'date_accessed':'2017-07-12 17:43:24'
       },
       '001':{  
          'marks':'80',
          'class':'9',
          'name':'AAA',
          'date_accessed':'2017-07-12 17:43:24'
       },
    }

现在,不知何故,我已经实现了使用这个等式按marks 对其进行排序

dict_sorted = sorted(my_dict, key=lambda x: int(my_dict[x]['marks']), reverse=True)

但这仅以排序方式给我keys,但我无法像上面那样生成新排序的字典。请在这里帮我按marks 对字典进行排序,并提供新的排序字典。谢谢。

编辑:我已经在 stackoverflow 中看到了很多类似 Sort a Python dictionary by value 和 Issue sorting a multi-dimensional dictionary that has non-numeric indices in Python 的帖子,但这些帖子无法提供我需要的结果。

【问题讨论】:

  • 您的目标字典与输入字典相同(除了您的错字)。
  • 字典是无序的。说“排序字典”是没有意义的。您最好的选择是使用有序映射,例如collections.OrderedDict。为什么你需要它“排序”呢?

标签: python python-2.7 sorting dictionary


【解决方案1】:

字典是无序的直到(包括)。仅订购了 字典的少数版本。正如documentation中所写:

考虑了这个新实现的顺序保留方面 实现细节,不应依赖(这可能 将来会发生变化,但希望有这个新的dict 在更改之前的几个版本的语言中实现 语言规范要求所有当前的保持顺序的语义 以及未来的 Python 实现;这也有助于保存 向后兼容旧版本的语言 随机迭代顺序仍然有效,例如Python 3.5)。

所以我们最好安全而不是抱歉,并且不要使用dict。

在collections 中有一个OrderedDict 类,它是一个字典,它维护元素添加方式的顺序。

因此我们现在可以像这样使用它:

from collections import OrderedDict

OrderedDict(sorted(my_dict.items(),key=lambda x:int(x[1]['marks']),reverse=True))

请注意,您必须使用.items() 来获取具有 键值 对的元组。然后,我们通过取值(元组的第二个元素)以及与 'marks' 键关联的值对元素进行排序。

如果您想要数值比较,您应该添加一个int(..) 调用,首先将它们转换为整数。

这会生成:

>>> OrderedDict(sorted(my_dict.items(),key=lambda x:int(x[1]['marks']),reverse=True))
OrderedDict([('005', {'name': 'EEE', 'date_accessed': '2017-07-12 17:43:42', 'class': '99', 'marks': '999'}), ('004', {'name': 'DDD', 'date_accessed': '2017-07-12 17:43:24', 'class': '50', 'marks': '100'}), ('003', {'name': 'CCC', 'date_accessed': '2017-07-12 17:43:24', 'class': '13', 'marks': '90'}), ('002', {'name': 'BBB', 'date_accessed': '2017-07-12 17:43:24', 'class': '10', 'marks': '90'}), ('001', {'name': 'AAA', 'date_accessed': '2017-07-12 17:43:24', 'class': '9', 'marks': '80'})])

OrderedDict 是 Python 中 vanilla 字典 的子类。所以dict支持的所有操作,OrderedDict也支持。

【讨论】:

  • 只订购了 dict 的 CPython-3.6 实现,该功能仅在少数版本中成为官方 python 功能,请参阅here
  • @jadsq:感谢您的评论。我将此添加到答案中。
【解决方案2】:

据我所知,在python中你不能真正对字典进行排序,我将使用以下代码:

def sort_dict_to_top_whatever(dict_to_sort, how_many_to_store):
    """
    function will sort the input dict and return the amount of the input number as top
    :param dict_to_sort: the dict with numbers at the values
    :param how_many_to_store: how much to take
    :return: the sorted dict
    """
    #                    -x: because we need to reverse sort:
    step1_sort_to_list = sorted(list(dict_to_sort.items()), key = lambda x: -int(x[1]["marks"]))
    step2_take_top = step1_sort_to_list[:how_many_to_store]
    step3_the_dict = {info[FIRST]: info[1] for info in step2_take_top}
    return step3_the_dict

然后:

sorted_dict = sort_dict_to_top_whatever(my_dict, len(my_dict))

【讨论】:

    【解决方案3】:

    使用你必须的行来获得你想要字典的正确索引顺序

    dict_sorted = sorted(my_dict, key=lambda x: int(my_dict[x]['marks']), reverse=True)
    

    然后使用新的索引顺序遍历字典,并添加到新字典中

    newly_ordered = {}
    for new_index in dict_sorted:
        # get the relevant item from the original dictionary
        item = file_list[new_index]
        print(item)
        # add to new dict
        newley_ordered = item
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-02
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2019-02-08
      相关资源
      最近更新 更多