Sorting List by Dictionary Values in Python

  • Share this:

Code introduction


This function sorts the list `arg1` based on the values in the dictionary `arg2`. If a key in `arg2` is not present in `arg1`, a `ValueError` is raised.


Technology Stack : Sorting, dictionary comprehension, lambda expression

Code Type : Sort function

Code Difficulty : Intermediate


                
                    
def aordify(arg1, arg2):
    try:
        return sorted(arg1, key=lambda x: arg2[x])
    except KeyError:
        raise ValueError("arg2 must be a subset of the keys in arg1")