Sort nested dictionary by value, and remainder by another value, in Python

前端 未结 4 1535
梦谈多话
梦谈多话 2020-11-30 03:11

Consider this dictionary format.

{\'KEY1\':{\'name\':\'google\',\'date\':20100701,\'downloads\':0},
 \'KEY2\':{\'name\':\'chrome\',\'date\':20071010,\'downlo         


        
4条回答
  •  日久生厌
    2020-11-30 03:35

    My other answer was wrong (as are most of the answers here)

    sorted_keys = sorted((key for key in outer_dict if outer_dict[key]['downloads']),
                         key=lambda x: (outer_dict[key]['downloads'],
                                        outer_dict[key]['downloads'])
                         reverse=True)
    
    sorted_keys += sorted((key for key in outer_dict if not outer_dict[key]['downloads']),
                          key=lambda x: outer_dict[key]['date'])
    

    This will create a list with the items that have been downloaded sorted in descending order at the front of it and the rest of the items that have not been downloaded sorted by date after those that have.

    But actually, the last part of Eli Courtwrights answer is the best.

提交回复
热议问题