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

前端 未结 4 1533
梦谈多话
梦谈多话 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:33

    You can pass a key function to sorted which returns a tuple containing the two things you wish to sort on. Assuming that your big dictionary is called d:

    def keyfunc(tup):
        key, d = tup
        return d["downloads"], d["date"]
    
    items = sorted(d.items(), key = keyfunc)
    

    You can do this with a lambda if you prefer, but this is probably more clear. Here's the equivalent lambda-based code:

    items = sorted(d.items(), key = lambda tup: (tup[1]["downloads"], tup[1]["date"]))
    

    Incidentally, since you mentioned that you wanted to sort by "downloads" first, the above two examples sort according to download counts in ascending order. However, from context it sounds like you might want to sort in decreasing order of downloads, in which case you'd say

    return -d["downloads"], d["date"]
    

    in your keyfunc. If you wanted something like sorting in ascending order for non-zero download numbers, then having all zero-download records after that, you could say something like

    return (-d["downloads"] or sys.maxint), d["date"]
    

提交回复
热议问题