代码之家  ›  专栏  ›  技术社区  ›  andrei

按特定顺序排列的词典列表

  •  0
  • andrei  · 技术社区  · 14 年前

    3 回复  |  直到 14 年前
        1
  •  4
  •   S.Lott    14 年前

    将“词典列表(每个文档一个)移到词典中,但顺序与原始列表不同”。

    这个新的词典有匹配的键。

    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.
    
        2
  •  1
  •   sth    14 年前

    ids = ...
    positions = {}
    for pos, id in enumerate(ids):
       positions[id] = pos
    
    docs = ...
    docs.sort(key=lambda doc: positions[doc['id']])
    
        3
  •  0
  •   Community CDub    8 年前

    最佳(一般)解决方案如下: reordering list of dicts arbitrarily in python