Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a list of dictionaries is sorted?

I have created a list of dictionaries:

l = []
d = {"a":1,"b",2}
l.append(d)
d = {"a":5,"b":6}
l.append(d)
d = {"a":3,"b":4}
l.append(d)

Now, how do I check whether the list of dictionaries is sorted or not based on the key a or key b?

like image 449
user2365346 Avatar asked Oct 28 '25 05:10

user2365346


2 Answers

print(l == sorted(l, key=lambda d:d["a"]))
False
like image 109
Dyno Fu Avatar answered Oct 29 '25 18:10

Dyno Fu


Just use the default check if something is sorted, but index before comparing:

k = "a"
all(l[i][k] <= l[i+1][k] for i in range(len(l) - 1))
like image 23
orlp Avatar answered Oct 29 '25 19:10

orlp