<p>How do I sort a list of dictionaries by a specific key's value? Given:</p>
<pre><code>[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]
</code></pre>
<p>When sorted by <code>name</code>, it should become:</p>
<pre><code>[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]
</code></pre>

[{'answer_id': 72950, 'author': 'Matej', 'author_id': 11457, 'author_profile': 'https://Stackoverflow.com/users/11457', 'pm_score': 5, 'selected': False, 'text': '<p>You have to implement your own comparison function that will compare the dictionaries by values of name keys. See <a href="http://wiki.python.org/moin/HowTo/Sorting" rel="noreferrer">Sorting Mini-HOW TO from PythonInfo Wiki</a></p>\n'}, {'answer_id': 73019, 'author': 'Bartosz Radaczyński', 'author_id': 985, 'author_profile': 'https://Stackoverflow.com/users/985', 'pm_score': 5, 'selected': False, 'text': "<p>I guess you've meant:</p>\n\n<pre><code>[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n</code></pre>\n\n<p>This would be sorted like this:</p>\n\n<pre><code>sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))\n</code></pre>\n"}, {'answer_id': 73044, 'author': 'pjz', 'author_id': 8002, 'author_profile': 'https://Stackoverflow.com/users/8002', 'pm_score': 7, 'selected': False, 'text': "<pre><code>my_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]\n\nmy_list.sort(lambda x,y : cmp(x['name'], y['name']))\n</code></pre>\n<p><code>my_list</code> will now be what you want.</p>\n<p>Or better:</p>\n<p>Since Python 2.4, there's a <code>key</code> argument is both more efficient and neater:</p>\n<pre><code>my_list = sorted(my_list, key=lambda k: k['name'])\n</code></pre>\n<p>...the lambda is, IMO, easier to understand than <code>operator.itemgetter</code>, but your mileage may vary.</p>\n"}, {'answer_id': 73050, 'author': 'Mario F', 'author_id': 3785, 'author_profile': 'https://Stackoverflow.com/users/3785', 'pm_score': 13, 'selected': True, 'text': '<p>The <a href="https://docs.python.org/library/functions.html#sorted" rel="noreferrer"><code>sorted()</code></a> function takes a <code>key=</code> parameter</p>\n<pre><code>newlist = sorted(list_to_be_sorted, key=lambda d: d[\'name\']) \n</code></pre>\n<p>Alternatively, you can use <a href="https://docs.python.org/library/operator.html#operator.itemgetter" rel="noreferrer"><code>operator.itemgetter</code></a> instead of defining the function yourself</p>\n<pre><code>from operator import itemgetter\nnewlist = sorted(list_to_be_sorted, key=itemgetter(\'name\')) \n</code></pre>\n<p>For completeness, add <code>reverse=True</code> to sort in descending order</p>\n<pre><code>newlist = sorted(list_to_be_sorted, key=itemgetter(\'name\'), reverse=True)\n</code></pre>\n'}, {'answer_id': 73098, 'author': 'efotinis', 'author_id': 12320, 'author_profile': 'https://Stackoverflow.com/users/12320', 'pm_score': 5, 'selected': False, 'text': "<pre><code>import operator\na_list_of_dicts.sort(key=operator.itemgetter('name'))\n</code></pre>\n\n<p>'key' is used to sort by an arbitrary value and 'itemgetter' sets that value to each item's 'name' attribute.</p>\n"}, {'answer_id': 73186, 'author': 'Owen', 'author_id': 12592, 'author_profile': 'https://Stackoverflow.com/users/12592', 'pm_score': 5, 'selected': False, 'text': "<p>You could use a custom comparison function, or you could pass in a function that calculates a custom sort key. That's usually more efficient as the key is only calculated once per item, while the comparison function would be called many more times.</p>\n\n<p>You could do it this way:</p>\n\n<pre><code>def mykey(adict): return adict['name']\nx = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]\nsorted(x, key=mykey)\n</code></pre>\n\n<p>But the standard library contains a generic routine for getting items of arbitrary objects: <code>itemgetter</code>. So try this instead:</p>\n\n<pre><code>from operator import itemgetter\nx = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age':10}]\nsorted(x, key=itemgetter('name'))\n</code></pre>\n"}, {'answer_id': 73465, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 8, 'selected': False, 'text': "<pre><code>import operator\n</code></pre>\n\n<p>To sort the list of dictionaries by key='name':</p>\n\n<pre><code>list_of_dicts.sort(key=operator.itemgetter('name'))\n</code></pre>\n\n<p>To sort the list of dictionaries by key='age':</p>\n\n<pre><code>list_of_dicts.sort(key=operator.itemgetter('age'))\n</code></pre>\n"}, {'answer_id': 2858683, 'author': 'Dologan', 'author_id': 222135, 'author_profile': 'https://Stackoverflow.com/users/222135', 'pm_score': 6, 'selected': False, 'text': "<p>If you want to sort the list by multiple keys, you can do the following:</p>\n<pre><code>my_list = [{'name':'Homer', 'age':39}, {'name':'Milhouse', 'age':10}, {'name':'Bart', 'age':10} ]\nsortedlist = sorted(my_list , key=lambda elem: &quot;%02d %s&quot; % (elem['age'], elem['name']))\n</code></pre>\n<p>It is rather hackish, since it relies on converting the values into a single string representation for comparison, but it works as expected for numbers including negative ones (although you will need to format your string appropriately with zero paddings if you are using numbers).</p>\n"}, {'answer_id': 16772049, 'author': 'kiriloff', 'author_id': 1141493, 'author_profile': 'https://Stackoverflow.com/users/1141493', 'pm_score': 5, 'selected': False, 'text': '<p>Using the <a href="https://en.wikipedia.org/wiki/Schwartzian_transform" rel="noreferrer">Schwartzian transform</a> from Perl,</p>\n<pre><code>py = [{\'name\':\'Homer\', \'age\':39}, {\'name\':\'Bart\', \'age\':10}]\n</code></pre>\n<p>do</p>\n<pre><code>sort_on = &quot;name&quot;\ndecorated = [(dict_[sort_on], dict_) for dict_ in py]\ndecorated.sort()\nresult = [dict_ for (key, dict_) in decorated]\n</code></pre>\n<p>gives</p>\n<pre><code>&gt;&gt;&gt; result\n[{\'age\': 10, \'name\': \'Bart\'}, {\'age\': 39, \'name\': \'Homer\'}]\n</code></pre>\n<p>More on the Perl Schwartzian transform:</p>\n<blockquote>\n<p>In computer science, the Schwartzian transform is a Perl programming\nidiom used to improve the efficiency of sorting a list of items. This\nidiom is appropriate for comparison-based sorting when the ordering is\nactually based on the ordering of a certain property (the key) of the\nelements, where computing that property is an intensive operation that\nshould be performed a minimal number of times. The Schwartzian\nTransform is notable in that it does not use named temporary arrays.</p>\n</blockquote>\n'}, {'answer_id': 23102554, 'author': 'Shank_Transformer', 'author_id': 2819862, 'author_profile': 'https://Stackoverflow.com/users/2819862', 'pm_score': 4, 'selected': False, 'text': '<p>Let\'s say I have a dictionary <code>D</code> with the elements below. To sort, just use the key argument in <code>sorted</code> to pass a custom function as below:</p>\n<pre><code>D = {\'eggs\': 3, \'ham\': 1, \'spam\': 2}\ndef get_count(tuple):\n    return tuple[1]\n\nsorted(D.items(), key = get_count, reverse=True)\n# Or\nsorted(D.items(), key = lambda x: x[1], reverse=True)  # Avoiding get_count function call\n</code></pre>\n<p>Check <a href="https://wiki.python.org/moin/HowTo/Sorting/#Key_Functions" rel="nofollow noreferrer">this</a> out.</p>\n'}, {'answer_id': 28094888, 'author': 'vvladymyrov', 'author_id': 1296661, 'author_profile': 'https://Stackoverflow.com/users/1296661', 'pm_score': 4, 'selected': False, 'text': '<p>Here is the alternative general solution - it sorts elements of a dict by keys and values.</p>\n<p>The advantage of it - no need to specify keys, and it would still work if some keys are missing in some of dictionaries.</p>\n<pre><code>def sort_key_func(item):\n    &quot;&quot;&quot; Helper function used to sort list of dicts\n\n    :param item: dict\n    :return: sorted list of tuples (k, v)\n    &quot;&quot;&quot;\n    pairs = []\n    for k, v in item.items():\n        pairs.append((k, v))\n    return sorted(pairs)\nsorted(A, key=sort_key_func)\n</code></pre>\n'}, {'answer_id': 39281050, 'author': 'abby sobh', 'author_id': 3135363, 'author_profile': 'https://Stackoverflow.com/users/3135363', 'pm_score': 4, 'selected': False, 'text': '<p>Using the <a href="https://en.wikipedia.org/wiki/Pandas_%28software%29" rel="noreferrer">Pandas</a> package is another method, though its runtime at large scale is much slower than the more traditional methods proposed by others:</p>\n<pre><code>import pandas as pd\n\nlistOfDicts = [{\'name\':\'Homer\', \'age\':39}, {\'name\':\'Bart\', \'age\':10}]\ndf = pd.DataFrame(listOfDicts)\ndf = df.sort_values(\'name\')\nsorted_listOfDicts = df.T.to_dict().values()\n</code></pre>\n<p>Here are some benchmark values for a tiny list and a large (100k+) list of dicts:</p>\n<pre><code>setup_large = &quot;listOfDicts = [];\\\n[listOfDicts.extend(({\'name\':\'Homer\', \'age\':39}, {\'name\':\'Bart\', \'age\':10})) for _ in range(50000)];\\\nfrom operator import itemgetter;import pandas as pd;\\\ndf = pd.DataFrame(listOfDicts);&quot;\n\nsetup_small = &quot;listOfDicts = [];\\\nlistOfDicts.extend(({\'name\':\'Homer\', \'age\':39}, {\'name\':\'Bart\', \'age\':10}));\\\nfrom operator import itemgetter;import pandas as pd;\\\ndf = pd.DataFrame(listOfDicts);&quot;\n\nmethod1 = &quot;newlist = sorted(listOfDicts, key=lambda k: k[\'name\'])&quot;\nmethod2 = &quot;newlist = sorted(listOfDicts, key=itemgetter(\'name\')) &quot;\nmethod3 = &quot;df = df.sort_values(\'name\');\\\nsorted_listOfDicts = df.T.to_dict().values()&quot;\n\nimport timeit\nt = timeit.Timer(method1, setup_small)\nprint(\'Small Method LC: \' + str(t.timeit(100)))\nt = timeit.Timer(method2, setup_small)\nprint(\'Small Method LC2: \' + str(t.timeit(100)))\nt = timeit.Timer(method3, setup_small)\nprint(\'Small Method Pandas: \' + str(t.timeit(100)))\n\nt = timeit.Timer(method1, setup_large)\nprint(\'Large Method LC: \' + str(t.timeit(100)))\nt = timeit.Timer(method2, setup_large)\nprint(\'Large Method LC2: \' + str(t.timeit(100)))\nt = timeit.Timer(method3, setup_large)\nprint(\'Large Method Pandas: \' + str(t.timeit(1)))\n\n#Small Method LC: 0.000163078308105\n#Small Method LC2: 0.000134944915771\n#Small Method Pandas: 0.0712950229645\n#Large Method LC: 0.0321750640869\n#Large Method LC2: 0.0206089019775\n#Large Method Pandas: 5.81405615807\n</code></pre>\n'}, {'answer_id': 42855105, 'author': 'forzagreen', 'author_id': 3495031, 'author_profile': 'https://Stackoverflow.com/users/3495031', 'pm_score': 6, 'selected': False, 'text': "<pre><code>a = [{'name':'Homer', 'age':39}, ...]\n\n# This changes the list a\na.sort(key=lambda k : k['name'])\n\n# This returns a new list (a is not modified)\nsorted(a, key=lambda k : k['name']) \n</code></pre>\n"}, {'answer_id': 45094029, 'author': 'uingtea', 'author_id': 4082344, 'author_profile': 'https://Stackoverflow.com/users/4082344', 'pm_score': 4, 'selected': False, 'text': "<p>Sometimes we need to use <code>lower()</code>. For example,</p>\n<pre><code>lists = [{'name':'Homer', 'age':39},\n  {'name':'Bart', 'age':10},\n  {'name':'abby', 'age':9}]\n\nlists = sorted(lists, key=lambda k: k['name'])\nprint(lists)\n# [{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}, {'name':'abby', 'age':9}]\n\nlists = sorted(lists, key=lambda k: k['name'].lower())\nprint(lists)\n# [ {'name':'abby', 'age':9}, {'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]\n</code></pre>\n"}, {'answer_id': 47892332, 'author': 'srikavineehari', 'author_id': 8709791, 'author_profile': 'https://Stackoverflow.com/users/8709791', 'pm_score': 4, 'selected': False, 'text': '<p>If you do not need the original <code>list</code> of <code>dictionaries</code>, you could modify it in-place with <code>sort()</code> method using a custom key function.</p>\n\n<p>Key function:</p>\n\n<pre><code>def get_name(d):\n    """ Return the value of a key in a dictionary. """\n\n    return d["name"]\n</code></pre>\n\n<p>The <code>list</code> to be sorted:</p>\n\n<pre><code>data_one = [{\'name\': \'Homer\', \'age\': 39}, {\'name\': \'Bart\', \'age\': 10}]\n</code></pre>\n\n<p>Sorting it in-place:</p>\n\n<pre><code>data_one.sort(key=get_name)\n</code></pre>\n\n<p>If you need the original <code>list</code>, call the <code>sorted()</code> function passing it the <code>list</code> and the key function, then assign the returned sorted <code>list</code> to a new variable:</p>\n\n<pre><code>data_two = [{\'name\': \'Homer\', \'age\': 39}, {\'name\': \'Bart\', \'age\': 10}]\nnew_data = sorted(data_two, key=get_name)\n</code></pre>\n\n<p>Printing <code>data_one</code> and <code>new_data</code>.</p>\n\n<pre><code>&gt;&gt;&gt; print(data_one)\n[{\'name\': \'Bart\', \'age\': 10}, {\'name\': \'Homer\', \'age\': 39}]\n&gt;&gt;&gt; print(new_data)\n[{\'name\': \'Bart\', \'age\': 10}, {\'name\': \'Homer\', \'age\': 39}]\n</code></pre>\n'}, {'answer_id': 58179903, 'author': 'Bejür', 'author_id': 7933218, 'author_profile': 'https://Stackoverflow.com/users/7933218', 'pm_score': 4, 'selected': False, 'text': "<p>I have been a big fan of a filter with lambda. However, it is not best option if you consider time complexity.</p>\n<h3>First option</h3>\n<pre><code>sorted_list = sorted(list_to_sort, key= lambda x: x['name'])\n# Returns list of values\n</code></pre>\n<h3>Second option</h3>\n<pre><code>list_to_sort.sort(key=operator.itemgetter('name'))\n# Edits the list, and does not return a new list\n</code></pre>\n<h3>Fast comparison of execution times</h3>\n<pre><code># First option\npython3.6 -m timeit -s &quot;list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]&quot; -s &quot;sorted_l=[]&quot; &quot;sorted_l = sorted(list_to_sort, key=lambda e: e['name'])&quot;\n</code></pre>\n<blockquote>\n<p>1000000 loops, best of 3: 0.736 µsec per loop</p>\n</blockquote>\n<pre><code># Second option\npython3.6 -m timeit -s &quot;list_to_sort = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}, {'name':'Faaa', 'age':57}, {'name':'Errr', 'age':20}]&quot; -s &quot;sorted_l=[]&quot; -s &quot;import operator&quot; &quot;list_to_sort.sort(key=operator.itemgetter('name'))&quot;\n</code></pre>\n<blockquote>\n<p>1000000 loops, best of 3: 0.438 µsec per loop</p>\n</blockquote>\n"}, {'answer_id': 59802559, 'author': 'swac', 'author_id': 10452855, 'author_profile': 'https://Stackoverflow.com/users/10452855', 'pm_score': 3, 'selected': False, 'text': '<p>If performance is a concern, I would use <code>operator.itemgetter</code> instead of <code>lambda</code> as built-in functions perform faster than hand-crafted functions. The <code>itemgetter</code> function seems to perform approximately 20% faster than <code>lambda</code> based on my testing.</p>\n<p>From <a href="https://wiki.python.org/moin/PythonSpeed" rel="noreferrer">https://wiki.python.org/moin/PythonSpeed</a>:</p>\n<blockquote>\n<p>Likewise, the builtin functions run faster than hand-built equivalents. For example, map(operator.add, v1, v2) is faster than map(lambda x,y: x+y, v1, v2).</p>\n</blockquote>\n<p>Here is a comparison of sorting speed using <code>lambda</code> vs <code>itemgetter</code>.</p>\n<pre><code>import random\nimport operator\n\n# Create a list of 100 dicts with random 8-letter names and random ages from 0 to 100.\nl = [{\'name\': \'\'.join(random.choices(string.ascii_lowercase, k=8)), \'age\': random.randint(0, 100)} for i in range(100)]\n\n# Test the performance with a lambda function sorting on name\n%timeit sorted(l, key=lambda x: x[\'name\'])\n13 µs ± 388 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n# Test the performance with itemgetter sorting on name\n%timeit sorted(l, key=operator.itemgetter(\'name\'))\n10.7 µs ± 38.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n# Check that each technique produces the same sort order\nsorted(l, key=lambda x: x[\'name\']) == sorted(l, key=operator.itemgetter(\'name\'))\nTrue\n</code></pre>\n<p>Both techniques sort the list in the same order (verified by execution of the final statement in the code block), but the first one is a little faster.</p>\n'}, {'answer_id': 69072597, 'author': 'Tms91', 'author_id': 7658051, 'author_profile': 'https://Stackoverflow.com/users/7658051', 'pm_score': 1, 'selected': False, 'text': '<p>As indicated by @Claudiu to @monojohnny in comment section of <a href="https://stackoverflow.com/a/73465/7658051">this answer</a>,<br> given:</p>\n<pre><code>list_to_be_sorted = [\n                      {\'name\':\'Homer\', \'age\':39}, \n                      {\'name\':\'Milhouse\', \'age\':10}, \n                      {\'name\':\'Bart\', \'age\':10} \n                    ]\n</code></pre>\n<p>to sort the list of dictionaries by key <code>\'age\'</code>, <code>\'name\'</code>\n<br>(like in SQL statement <code>ORDER BY age, name</code>), you can use:</p>\n<pre><code>newlist = sorted( list_to_be_sorted, key=lambda k: (k[\'age\'], k[\'name\']) )\n</code></pre>\n<p>or, likewise</p>\n<pre><code>import operator\nnewlist = sorted( list_to_be_sorted, key=operator.itemgetter(\'age\',\'name\') )\n</code></pre>\n<p><code>print(newlist)</code></p>\n<blockquote>\n<p>[{\'name\': \'Bart\', \'age\': 10},<br>  {\'name\': \'Milhouse\', \'age\': 10},<br>\n{\'name\': \'Homer\', \'age\': 39}]</p>\n</blockquote>\n'}, {'answer_id': 72939809, 'author': 'alex', 'author_id': 4444742, 'author_profile': 'https://Stackoverflow.com/users/4444742', 'pm_score': 0, 'selected': False, 'text': "<p>sorting by multiple columns, while in descending order on some of them:\nthe cmps array is global to the cmp function, containing field names and inv == -1 for desc 1 for asc</p>\n<pre><code>def cmpfun(a, b):\n    for (name, inv) in cmps:\n        res = cmp(a[name], b[name])\n        if res != 0:\n            return res * inv\n    return 0\n\ndata = [\n    dict(name='alice', age=10), \n    dict(name='baruch', age=9), \n    dict(name='alice', age=11),\n]\n\nall_cmps = [\n    [('name', 1), ('age', -1)], \n    [('name', 1), ('age', 1)], \n    [('name', -1), ('age', 1)],]\n\nprint 'data:', data\nfor cmps in all_cmps: print 'sort:', cmps; print sorted(data, cmpfun)\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/72899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12398/']