Sorting Python lists based on dictionary keys in Python

Solution 2 utilizes a generator expression to locate the index of the first key from the key list in each dictionary. This index is then used as the sort key. If a dictionary doesn’t contain any of the keys, it is assigned a sort key that ensures it is sorted to the end. To achieve this, the entire content is returned instead of a specific element, and instead of returning a certain value, the content is returned.
Solution 1 uses the keys in each dictionary as the sort key by converting them into a list.
In Solution 2, one approach is to…
Solution 3, as mentioned by @Mike, involves casting the outcome of either … or … as …

Solution 1:

Indeed, dict.get is the accurate (or at least, the most straightforward) method.

sorted(trial_list, key=trial_dict.get)

According to Mark Amery’s comment, the explicit lambda that is equivalent:

sorted(trial_list, key=lambda x: trial_dict[x])

It could be more advantageous for a couple of reasons.

  1. The visible sort expression can be edited right away.
  2. It does not prevent errors from occurring if the list contains an element that is not present in the dictionary.

Solution 2:

In the


builtin function (or the


method of lists), the crucial argument must be a function that maps the items of the list being sorted to the desired sorting values. Therefore, the desired outcome is as follows:

sorted(trial_list, key=lambda x: trial_dict[x])

Frequently Asked Questions