Skip to content
Fix Code Error

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

March 13, 2021 by Code Error
Posted By: Anonymous

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}, {'name':'Bart', 'age':10}]

When sorted by name, it should become:

[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]

Solution

It may look cleaner using a key instead a cmp:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 

or as J.F.Sebastian and others suggested,

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name')) 

For completeness (as pointed out in comments by fitzgeraldsteele), add reverse=True to sort descending

newlist = sorted(l, key=itemgetter('name'), reverse=True)
Answered By: Mario

Related Articles

  • Combining items using XSLT Transform
  • How do I merge two dictionaries in a single…
  • How do operator.itemgetter() and sort() work?
  • Convert array to nested JSON object - Angular Material tree
  • Using custom std::set comparator
  • What does this symbol mean in JavaScript?
  • How can I manually compile a svelte component down…
  • How to sort an array in descending order in Ruby
  • How to add 'load more' functionality to items on a…
  • How do I sort a dictionary by value?
  • When I'm testing a web app by JUnit and Mockito I…
  • How to check balanced parentheses using emu8086
  • Why does C++ code for testing the Collatz conjecture…
  • Display Grid does not work in Polymer correctly
  • Centering in CSS Grid
  • What is The Rule of Three?
  • Why doesn't Python have a sign function?
  • Trouble with Next js + Express deployment using Zeit Now
  • Binding complex object to a component
  • Reference — What does this symbol mean in PHP?
  • How do I include certain conditions in SQL Count
  • How to create a property for a List
  • Making a map of composite types typescript
  • How to append multiple items in one line in Python
  • Split JSON python string to pass to function
  • Array vs List in recursive F# function
  • How to separate opening and closing tag by…
  • python dictionary sorting in descending order based…
  • How to convert lower case to upper case and vice…
  • backbone js, Update view on model change
  • How to show title in hover - css / jquery
  • no match for ‘operator
  • Vue order list view
  • AppCompat v7 r21 returning error in values.xml?
  • Dart core element core-collapse
  • fasm x64 windows gdi programming struggles - call to…
  • Efficient Algorithm for Bit Reversal (from…
  • How to extend and merge a list of objects with…
  • Composition or Inheritance for classes with almost…
  • How to make vuetify navigation drawer to close group…
  • Remove similar tuple from dictionary of tuples
  • How to simplify sequential logic design by…
  • replace n to new line on vuejs
  • jQuery.on() Delegation: Slightly complex selector…
  • Argument Exception "Item with Same Key has already…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Polymer 1.0: Sorting iron-list
  • Sorting Python list based on the length of the string
  • Perfomance issues with large number of elements in…
  • Dictionary returning a default value if the key does…
  • C++ template,typename and operator
  • Valid values for android:fontFamily and what they map to?
  • Sort table rows In Bootstrap
  • BTable Filter with a Function
  • Replacing a 32-bit loop counter with 64-bit…
  • Call child component method from parent class - Angular
  • compareTo with primitives -> Integer / int
  • What is the copy-and-swap idiom?
  • How to specify line breaks in a multi-line flexbox layout?
  • How do I sort an observable collection?
  • Sort a list by multiple attributes?
  • How to select top N of two groups and aggregate the…
  • Jetpack Compose and Hilt Conflict
  • What is a NullReferenceException, and how do I fix it?
  • Make drag & drop sort order in Vue.js start at 1, not 0
  • LINQ where clause with lambda expression having OR…
  • Sorting Backbone Collections
  • HashSet vs. List performance
  • in doesn't call method on item change
  • Show only certain items at certain condition on…
  • How to implement an STL-style iterator and avoid…
  • Overloading operators in typedef structs (c++)
  • Are dictionaries ordered in Python 3.6+?
  • I do not use TBB, but I get linker errors related to TBB
  • Getting key with maximum value in dictionary?
  • Pandas - Merge rows of dataframe that have a shared value
  • Retrieving a list of Dictionaries from Nested…
  • Having trouble making this assembly procedure work…
  • Kodein + Ktor = mutation attempt of frozen…
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • How can I return the rendered HTML of a Svelte component?
  • Find the most common element in a list
  • Sorting using Comparator- Descending order (User…
  • python max function using 'key' and lambda expression
  • Polymer 1.x: Two-way databinding for paper-dropdown-menu
  • Implementing autocomplete
  • C++ Need help sorting a 2D string array
  • How to convert string to expression ( value ) in…
  • How to compare LocalDate instances Java 8
  • LINQ select in C# dictionary
  • Dialogflow to Firestore using Inline Fulfillment -…
  • Case insensitive access for generic dictionary
  • Why is there no SortedList in Java?
  • How to sort a list of lists by a specific index of…
  • How to filter a RecyclerView with a SearchView
  • What is a lambda expression in C++11?
  • How to create multiple object of same data class kotlin
  • Passing string into a lambda function
  • useSWR conditional fetch and react-boostrap Accordion
  • ImportError: No module named dateutil.parser

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

jQuery to loop through elements with the same class

Next Post:

How can I convert an image into Base64 string using JavaScript?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error