views:

66

answers:

3

I am using Python 2.6 and I have two data stores. Querying the first one returns a list of document IDs in a specific order. I look up all the documents at once in the second data store using these IDs, which returns a list of dictionaries (one for each doc), but not in the same order as the original list. I now need to re-sort this list of dictionaries so that the documents are in the order that their IDs were in the first list. What's the best way of doing this?

+4  A: 

Don't.

Move your "list of dictionaries (one for each doc), but not in the same order as the original list" into a dictionary.

This new dictionary-of-dictionaries has the matching key.

Then go through your first list in it's order and find items in the dictionary-of-dictionaries that match.

some_list= query_data_store_1()
some_other_list= query_data_store_2( some_list )

dict_of_dict = dict( (d['key'], d) for d in some_other_list )

for item in some_list:
    other_item = dict_of_dict[ item['key'] ]

    # Now you have item from the first list matching item from the second list.
    # And it's in order by the first list.
S.Lott
dict_of_dict = dict( d['id'], d for d in some_other_list )
kurosch
+1  A: 

You could build a separate dictionary mapping ids to positions and use that to order the documents:

ids = ...
positions = {}
for pos, id in enumerate(ids):
   positions[id] = pos

docs = ...
docs.sort(key=lambda doc: positions[doc['id']])
sth
A: 

The best (and general) solution seems to be given here: http://stackoverflow.com/questions/3301406/reordering-list-of-dicts-arbitrarily-in-python

andrei