How do I sort a list of dictionaries by a value of the dictionary?

后端 未结 18 2875
半阙折子戏
半阙折子戏 2020-11-21 04:06

I have a list of dictionaries and want each item to be sorted by a specific value.

Take into consideration the list:

[{\'name\':\'Homer\', \'age\':39},         


        
18条回答
  •  既然无缘
    2020-11-21 05:08

    Using the Pandas package is another method, though its runtime at large scale is much slower than the more traditional methods proposed by others:

    import pandas as pd
    
    listOfDicts = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
    df = pd.DataFrame(listOfDicts)
    df = df.sort_values('name')
    sorted_listOfDicts = df.T.to_dict().values()
    

    Here are some benchmark values for a tiny list and a large (100k+) list of dicts:

    setup_large = "listOfDicts = [];\
    [listOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10})) for _ in range(50000)];\
    from operator import itemgetter;import pandas as pd;\
    df = pd.DataFrame(listOfDicts);"
    
    setup_small = "listOfDicts = [];\
    listOfDicts.extend(({'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}));\
    from operator import itemgetter;import pandas as pd;\
    df = pd.DataFrame(listOfDicts);"
    
    method1 = "newlist = sorted(listOfDicts, key=lambda k: k['name'])"
    method2 = "newlist = sorted(listOfDicts, key=itemgetter('name')) "
    method3 = "df = df.sort_values('name');\
    sorted_listOfDicts = df.T.to_dict().values()"
    
    import timeit
    t = timeit.Timer(method1, setup_small)
    print('Small Method LC: ' + str(t.timeit(100)))
    t = timeit.Timer(method2, setup_small)
    print('Small Method LC2: ' + str(t.timeit(100)))
    t = timeit.Timer(method3, setup_small)
    print('Small Method Pandas: ' + str(t.timeit(100)))
    
    t = timeit.Timer(method1, setup_large)
    print('Large Method LC: ' + str(t.timeit(100)))
    t = timeit.Timer(method2, setup_large)
    print('Large Method LC2: ' + str(t.timeit(100)))
    t = timeit.Timer(method3, setup_large)
    print('Large Method Pandas: ' + str(t.timeit(1)))
    
    #Small Method LC: 0.000163078308105
    #Small Method LC2: 0.000134944915771
    #Small Method Pandas: 0.0712950229645
    #Large Method LC: 0.0321750640869
    #Large Method LC2: 0.0206089019775
    #Large Method Pandas: 5.81405615807
    

提交回复
热议问题