按值对多维字典排序,并用Python返回新排序的字典

2024-06-11 04:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的字典样本。在

    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对其进行排序,因此生成的字典将如下所示

^{pr2}$

现在,不知怎么的,我已经实现了用这个等式对它进行排序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,但是这些帖子不能提供我需要的结果。在


Tags: namedatedictionary字典排序mydict帖子
3条回答

用你必须的那一行得到你想要字典的正确索引顺序

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

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

^{pr2}$

据我所知,在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

然后:

^{pr2}$

字典是无序的直到(包括)。只有少数版本的字典才被订购。如documentation中所写:

The order-preserving aspect of this new implementation is considered an implementation detail and should not be relied upon (this may change in the future, but it is desired to have this new dict implementation in the language for a few releases before changing the language spec to mandate order-preserving semantics for all current and future Python implementations; this also helps preserve backwards-compatibility with older versions of the language where random iteration order is still in effect, e.g. Python 3.5).

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

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

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

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

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

如果你想进行数值比较,你应该先添加一个int(..)调用,把它们转换成整数。在

这将产生:

^{pr2}$

OrderedDict是Python中的香草字典的子类。因此,dict支持的所有操作也受OrderedDict的支持。在

相关问题 更多 >