Skip Navigation

Python question: How to convert list to sort with multiple keys?

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

3 comments