9
submitted 1 day ago* (last edited 1 day ago) by [email protected] to c/[email protected]

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))

you are viewing a single comment's thread
view the rest of the comments
[-] [email protected] 5 points 1 day ago

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.

this post was submitted on 19 Jun 2025
9 points (84.6% liked)

Programming

20987 readers
70 users here now

Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!

Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.

Hope you enjoy the instance!

Rules

Rules

  • Follow the programming.dev instance rules
  • Keep content related to programming in some way
  • If you're posting long videos try to add in some form of tldr for those who don't want to watch videos

Wormhole

Follow the wormhole through a path of communities [email protected]



founded 2 years ago
MODERATORS