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

0 votes

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

Take into consideration the array below,

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

When sorted by name, should become

[{'name':'Bart', 'age':10}, {'name':'Homer', 'age':39}]
Apr 23, 2020 in Python by kartik
• 37,510 points
556 views

1 answer to this question.

0 votes

Hello @kartik,

import operator

To sort the list of dictionaries by key='name':

list_of_dicts.sort(key=operator.itemgetter('name'))

To sort the list of dictionaries by key='age':

list_of_dicts.sort(key=operator.itemgetter('age'))

hope this works!!

Thank You!!

answered Apr 23, 2020 by Niroj
• 82,880 points

Related Questions In Python

+2 votes
2 answers

In a list of dictionaries, how can I find the minimum calue in a common dictionary field.

There are several options. Here is a ...READ MORE

answered Apr 10, 2018 in Python by charlie_brown
• 7,720 points
1,093 views
0 votes
1 answer

How do I sort a dictionary by value?

It is not possible to sort a ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 58,090 points
553 views
0 votes
1 answer

How do I sort a dictionary by value?

If you construct a dictionary with the ...READ MORE

answered Mar 13, 2019 in Python by Trisha
451 views
0 votes
0 answers

How do I sort a dictionary by value?

I have some dictionary of values that ...READ MORE

Sep 21, 2022 in Python by Samuel
• 460 points
302 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,082 views
0 votes
1 answer
0 votes
1 answer

How do I get the number of elements in a list?

Hello, The len() function can be used with several different ...READ MORE

answered Nov 18, 2020 in Python by Niroj
• 82,880 points
447 views
0 votes
1 answer

How do I add a link from the Django admin page of one object to the admin page of a related object?

Hello @kartik, Set show_change_link to True (False by default) in your inline ...READ MORE

answered Jun 12, 2020 in Python by Niroj
• 82,880 points
9,964 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP