When sorting on a list of dictionaries, it is possible to ensure consistency and the desired sort-order by specifying one or more keys.
For example, given a list L:
L = [{'a':1, 'b':2}, {'b':1, 'a':2}]
sorted(L, key=lambda dic:dic['a'])
returns
[ {'a': 1, 'b': 2} , {'a': 2, 'b': 1} ]
Similarly,
sorted(L, key=lambda dic:dic['b'])
returns
[ {'a': 2, 'b': 1} , {'a': 1, 'b': 2} ]
When not providing a key, i.e. just using sorted(L)
I am observing a sort order identical to the first sort expression. How exactly is a key chosen when not provided?
Background:
My final goal is to write a generic comparator (self.__eq__
) for a custom class, the basis of equality for which will be a number of properties one or more of which may be list of dictionaries. Since it is difficult to provide a sort key as fields within the dictionary that forms the list may not be known beforehand I was considering skipping the use of a key altogether to force the default. My gut feeling is that sorted
will yield the same result for a compound type regardless of original order in the absence of a key, but I haven't found any documentation to support this. Can someone explain?
Edit: I cannot understand why this was marked as a duplicate of the solution to explanation for dict.__cmp__
? I am trying to sort a list, not a dictionary. I do not care how the constituent dictionaries are ordered but what matters is the place of any dictionary in the list for list vs list comparison. With a normal list once could do set(L1)==set(L2)
to compare contents, however, my goal is try and compare two lists when the contents are dictionaries and this is why I need to sort them.