4

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

IN = [{
        "id": "a", 
        "val": "Value", 
        "val1": "Value1"
 }, 
 {
        "id": "b", 
        "val": "Value", 
        "val1": "Value1"
 }, 
 {
        "id": "c", 
        "val": "Value", 
        "val1": "Value1"
 }]

sortValue = ['b','c','a']

I want the output

OUT  = [{
        "id": "b", 
        "val": "Value", 
        "val1": "Value1"
    }, 
    {
        "id": "c", 
        "val": "Value", 
        "val1": "Value1"
    },
    {
        "id": "a", 
        "val": "Value", 
        "val1": "Value1"
    }]

How to get something like this?

I have tried:

OUT = []
for xx in sortValue:
    for x in IN:
        if x['id'] == xx:
            OUT.append(x)
print OUT
del OUT

But value in dict is mixed. [{'val1': 'Value1', 'id': 'b', 'val': 'Value'}, {'val1': 'Value1', 'id': 'c', 'val': 'Value'}, {'val1': 'Value1', 'id': 'a', 'val': 'Value'}]

fredtantini
  • 15,966
  • 8
  • 49
  • 55
user7172
  • 874
  • 4
  • 16
  • 31

2 Answers2

17

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.

fredtantini
  • 15,966
  • 8
  • 49
  • 55
1

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]
BlackJack
  • 4,476
  • 1
  • 20
  • 25