Sort list of dictionaries by another list

前端 未结 2 1803
没有蜡笔的小新
没有蜡笔的小新 2021-01-26 23:56

Sort list of dictionaries by another list. I have got list with dictionaries (IN) and I want to sort this by another list (sortValue).

         


        
相关标签:
2条回答
  • 2021-01-27 00:32

    Build a dictionary that maps IDs to the dictionary with that ID and then go through your sortValue list and pick the dictionary for each ID value:

    id2dict = dict((d['id'], d) for d in IN)
    OUT = [id2dict[x] for x in sortValue]
    
    0 讨论(0)
  • 2021-01-27 00:41

    You can also use the key parameter of the sorted function. In your case, you want the index of sortValue for the id of each item on the list:

    >>> pprint(sorted(IN,key=lambda x:sortValue.index(x['id'])))
    [{'id': 'b', 'val': 'Value', 'val1': 'Value1'},
     {'id': 'c', 'val': 'Value', 'val1': 'Value1'},
     {'id': 'a', 'val': 'Value', 'val1': 'Value1'}]
    

    More on sorting with python on its wiki.

    0 讨论(0)
提交回复
热议问题