I desperately need some Python help. In short, i want to use multiple keys at once for sorting a dictionary. I have a list of keys and don’t know how to convert it to the required list.
This is a single key. The self.items
is a list of dictionaries, where d[key]
is resolved to the actual key name such as “core_name”, that the list is then sorted as. This works as expected for single sort, but not for multiple.
key = "core_name"
self.items = sorted(self.items, key=lambda d: d[key])
key = "label"
self.items = sorted(self.items, key=lambda d: d[key])
Problem is, sorting it multiple times gives me wrong results. The keys need to be called in one go. I can do that manually like this:
self.items = sorted(self.items, key=lambda d: (d["core_name"], d["label"]))
But need it programmatically to assign a list of keys. The following does not work (obviously). I don’t know how to convert this into the required form:
# Not working!
keys = ["core_name", "label"]
self.items = sorted(self.items, key=lambda d: d[keys])
I somehow need something like a map function I guess? Something that d[keys]
is replaced by “convert each key in keys into a list of d[key]”. This is needed inside the lambda, because the key/value pair is dynamically read from self.items
.
Is it understandable what I try to do? Has anyone an idea?
Edit: Solution by Fred: https://beehaw.org/post/20656674/4826725
Just use comprehension and create a tuple in place: sorted(items, key=lambda d: tuple(d[k] for k in keys))
Inside the
lambda
expression you can have a comprehension to unpack thekeys
list to get the same sort of uplet as your “manual” example, like this:>>> items = [{"core_name": "a", "label": "b"},{"core_name": "c", "label": "d"}, ] >>> keys = ["core_name", "label"] >>> tuple(items[0][k] for k in keys) ('a', 'b') >>> sorted(items, key=lambda d: tuple(d[k] for k in keys)) [{'core_name': 'a', 'label': 'b'}, {'core_name': 'c', 'label': 'd'}]
Oh now this looks so obvious! Thank you and it works. Man Python might has its shortcomings, but it can be so elegant and easy to do so complex stuff in short time.
Just as a side note, after I created this topic, was curious to ask a local programming LLM Ai model. I usually don’t use Ai, but was curious to if it could help here finding the solution. I provided the entire post and it gave me the correct answer, basically the same as yours. Just a curiosity.
deleted by creator