How do I sort a list of dictionaries by a value of the dictionary?
The sorted()
function takes a key=
parameter
newlist = sorted(list_to_be_sorted, key=lambda d: d['name'])
Alternatively, you can use operator.itemgetter
instead of defining the function yourself
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
For completeness, add reverse=True
to sort in descending order
newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)
How do I sort a dictionary by value?
Python 3.7+ or CPython 3.6
Dicts preserve insertion order in Python 3.7+. Same in CPython 3.6, but it's an implementation detail.
>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
or
>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
Older Python
It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.
For instance,
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x
will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x
.
And for those wishing to sort on keys instead of values:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
In Python3 since unpacking is not allowed we can use
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
If you want the output as a dict, you can use collections.OrderedDict
:
import collections
sorted_dict = collections.OrderedDict(sorted_x)
Python: How to sort list of dictionaries by value and index
It appears that you're looking for the text
field as a secondary sort key. The easiest way is to simply use a tuple for your keys, in priority order:
sorted(data, key=lambda x: (x['value'], x['text']) )
Does that yield what you need? Output:
[{'text': 'a', 'value': 1}, {'text': 'b', 'value': 1}, {'text': 'j', 'value': 2}, {'text': 'x', 'value': 2}, {'text': 'k', 'value': 3}, {'text': 'm', 'value': 3}, {'text': 'b', 'value': 50}, {'text': 'k', 'value': 50}, {'text': 'y', 'value': 52}]
The values (k, 50) and (b, 50) are now in the other order; I'm hopeful that I read your mind correctly.
UPDATE per OP clarification
I checked the docs. Python's sort
method is stable, so you don't need the second sort key at all: in case of a tie, sort
will maintain the original ordering:
>>> data.sort(key= lambda x:x['value'])
>>> data
[{'text': 'a', 'value': 1}, {'text': 'b', 'value': 1}, {'text': 'j', 'value': 2}, {'text': 'x', 'value': 2}, {'text': 'k', 'value': 3}, {'text': 'm', 'value': 3}, {'text': 'k', 'value': 50}, {'text': 'b', 'value': 50}, {'text': 'y', 'value': 52}]
... and this is what you requested.
Sort a list of dictionaries without knowing the keys/values
One solution is to use dict.get
. If the key doesn't exist in dictionary it returns None
(or other default value if you want):
sorted_list = sorted(list_to_be_sorted, key=lambda k: k.get('name'))
sort list of dictionaries by the value of the dictionary
Starting from python 3.7 dictionaries are insertion ordered, so you could do it in the following way:
lst = [dict(sorted(d.items(), key=lambda x: x[1])) for d in lst]
Sort a list of dicts by each dicts key
Using the keys in each dict as sort key works by converting them into a list:
>>> sorted(dicts, key=lambda d: list(d.keys()))
[{1.0: (-1, 0)},
{2.0: (0, -2)},
{3.605551275463989: (-2, -3)},
{3.605551275463989: (3, 2)},
{4.47213595499958: (-2, -4)},
{5.830951894845301: (3, -5)}]
Sort a list by value of a dict python
New Answer
- Create class
selection_sort
which hasget_sorted()
method that will sort the list based on dictionary values using selection sort. - Here we compare two value and if first value is greater than second, than swap both the values. Repeat this step until entire list is sorted.
class selection_sort:
"""Sort the list based on dictionary value using selection sort."""
def __init__(self,L):
self.months = {"January": 1, "February": 2, "March": 3, "April": 4,
"May": 5,
"June": 6, "July": 7, "August": 8, "September": 9,
"October": 10, "November": 11, "December": 12}
self.L = L
def get_sorted(self):
""" sorting list."""
month_num = [self.months[i] for i in self.L]
flag = True # set Flag is True to enter the loop.
while flag:
flag = False # set Flag to False for no swaping done
for i in range(len(month_num)-1):
if month_num[i] > month_num[i+1]:
flag = True # set Flag to False if no swaping is done
# swap
month_num[i], month_num[i+1] = month_num[i+1], month_num[i]
L = [k for k, v in self.months.items() if v in month_num]
print(L)
return L
Test Case
Test which you have written is comparing
L
withExpected
. It should compareactual
withexpected
.self.assertEqual(L, expected)
Also, expected =
["March", "May", "December", "October", "September"]
is incorrect. It should have been["March", "May","September", "October", "December"]
import unittest
from selectionSort import selection_sort
# @unittest.skip("")
class TestInPlace(unittest.TestCase):
def test_1(self):
L = ["December", "September", "March", "October", "May"]
obj = selection_sort(L)
actual = obj.get_sorted()
expected = ["March", "May","September", "October", "December"]
self.assertEqual(actual, expected)
Old Answer
Try this,
#creating list L1
L1 = [months[L[i]] for i in range(len(L))]
print(L1)
#sorting list using algorithm selection sort
for i in range(1,len(L1)):
j = 0
if L1[j] > L1[i] :
L1[j], L1[i] = L1[i] ,L1[j]
print(L1)
#Replacing values with key
sorted_list = [ k for k,v in months.items() for i in L1 if i == v]
print(sorted_list)
How to sort a dictionary by values which contain lists in python
Sorted in python
Use this code:
sorted(Dict.items(), key=lambda x: x[1][1],reverse=True)
Output:
[('Key4', ['LONG_A', 9]), ('Key3', ['LONG', 7]), ('Key1', ['LONG', 1])]
Related Topics
Pandas To_Html() Truncates String Contents
Pass Input/Variables to Command/Script Over Ssh Using Python Paramiko
Standard_Init_Linux.Go:178: Exec User Process Caused "Exec Format Error"
Os.Walk Without Hidden Folders
Why Does "A == X or Y or Z" Always Evaluate to True
How to Unnest (Explode) a Column in a Pandas Dataframe, into Multiple Rows
Actual Meaning of 'Shell=True' in Subprocess
Why Can't I Call Read() Twice on an Open File
What Does the 'B' Character Do in Front of a String Literal
Split Strings into Words With Multiple Word Boundary Delimiters
What Are Iterator, Iterable, and Iteration
Use 'Import Module' or 'From Module Import'
Selenium in Python: Nosuchelementexception: Message: No Such Element: Unable to Locate Element
What Do _Init_ and Self Do in Python