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
?
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))
As discussed in this answer, you can efficiently check if a list is sorted using:
all(l[i] <= l[i+1] for i in xrange(len(l)-1))
To support a custom key, you can define something like
def is_sorted(iterable, key=None):
if key is None:
key = lambda x : x
return all(key(iterable[i]) <= key(iterable[i+1]) for i in xrange(len(iterable)-1))
In this case, you can just use a simple lambda function looking up the dictionary values as the key (assuming all elements are dicts containing a
and b
), e.g.
# Check if list of dictionaries are sorted by value of 'a'
>>> is_sorted(l, key=lambda x: x["a"])
# Check if list of dictionaries are sorted by value of 'b'
>>> is_sorted(l, key=lambda x: x["b"])
# Check if list of dictionaries are sorted by value of 'a', then 'b'
>>> is_sorted(l, key=lambda x: (x["a"], x["b"]))