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?
print(l == sorted(l, key=lambda d:d["a"]))
False
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With