pythonpython-3.xalibaba-cloudalibaba-cloud-ecs

How do I sort a list which is a value of dictionaries?


I need to sort a list which is a value of dictionaries by using a function with less computation cost. I would not able to share the original code, so please help me with the following example.

I tried with the standard approach, I parsed the values, used the intermediate list to sort and stored it in the new dictionary which is highly computation intensive. I am trying to streamline it, for that, I am expecting any suggestions or ways to incorporate.

Input

a= {'a':1, 'b': [2,8,4,3], 'c':['c',5,7,'a',6]}

Output

a= {'a':1, 'b': [2,3,4,8], 'c':['a','c',5,6,7]}


Solution

  • You do not need to sort the dict, you need to sort all values that are lists inside your dict. You do not need to create any new objects at all:

    a= {'a':1, 'b': [2,8,4,3], 'c':['c',5,7,'a',6]} # changed c and a to be strings
    
    for e in a:
        if isinstance(a[e],list):
            a[e].sort()         # inplace sort the lists
    
    print(a)
    

    Output:

    {'a': 1, 'c': [5, 6, 7, 'a', 'c'], 'b': [2, 3, 4, 8]}
    

    This does not create new dicts nor does it create new lists - it simply sorts the list in-place. You can not get much faster/less computational then that unless you have special domainknowledge about your lists that would make programming a specialized in-place-sorter as replacement for list.sort() viable.


    On Python 3 (thanks @Matthias Profil) comparison between int ansd str give TypeError - you can "fix" that with some optional computation ( inspired by answers at: python-list-sort-query-when-list-contains-different-element-types ):

    def IsString(item):    
        return isinstance(item,str)
    def IsInt(item):
        return isinstance(item,int)
    
    a= {'a':1, 'b': [2,8,4,3], 'c':['c',5,7,'a',6]} # changed c and a to be strings
    
    for e in a:
        if isinstance(a[e],list):
            try:
                a[e].sort()         # inplace sort the lists
            except TypeError:
                str_list = sorted(filter(IsString,a[e]))
                int_list = sorted(filter(IsInt,a[e]))
                a[e] = int_list + str_list # default to numbers before strings
    
    print(a)