开发者

Sorting list of dictionaries according to specific order

开发者 https://www.devze.com 2023-01-13 11:03 出处:网络
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 o开发者_如何学Pythonnce in the second data s

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 o开发者_如何学Pythonnce 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?


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.


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']])


The best (and general) solution seems to be given here: reordering list of dicts arbitrarily in python

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号