8
submitted 2 days ago* (last edited 2 days 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] 6 points 2 days ago

A Python-specific question is better suited to the [email protected] community instead of the general programming one.

this post was submitted on 19 Jun 2025
8 points (78.6% liked)

Programming

21026 readers
204 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