Is there a function in the python standard library to check if a list is unique based on one of the dictionary properties?
Something like this:
is_unique(dict_list, prop="x")
result:
{"x": 1, "y": 2}, {"x": 2, "y": 2}, {"x": 2, "y": 3} <- False
{"x": 1, "y": 2}, {"x": 2, "y": 2}, {"x": 3, "y": 3} <- True
You can naively do:
def is_unique(dcts, prop):
return len(dcts) == len(set(d[prop] for d in dcts))
This assumes that the values d[prop]
are hashable. If you have long lists, you might want to break early (when encountering the first duplicate) while building the prop set, as does
U9-Forward's solution.