Sort a list based on dictionary values in python?

前端 未结 2 1363
不知归路
不知归路 2020-12-11 01:12

Say I have a dictionary and then I have a list that contains the dictionary\'s keys. Is there a way to sort the list based off of the dictionaries values?

I have bee

相关标签:
2条回答
  • 2020-12-11 01:29

    The key argument in the sorted builtin function (or the sort method of lists) has to be a function that maps members of the list you're sorting to the values you want to sort by. So you want this:

    sorted(trial_list, key=lambda x: trial_dict[x])
    
    0 讨论(0)
  • 2020-12-11 01:44

    Yes dict.get is the correct (or at least, the simplest) way:

    sorted(trial_list, key=trial_dict.get)
    

    As Mark Amery commented, the equivalent explicit lambda:

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

    might be better, for at least two reasons:

    1. the sort expression is visible and immediately editable
    2. it doesn't suppress errors (when the list contains something that is not in the dict).
    0 讨论(0)
提交回复
热议问题