【问题标题】:Sort a dictionary using index position of keys in a base list使用基本列表中键的索引位置对字典进行排序
【发布时间】:2013-02-02 07:57:51
【问题描述】:

我有一个基本列表

li = ['fca', 'fc_add', 'fca_2', 'fcadd_2', 'Red_Exis', 'G_Exis', 'P_Exis', 'fam_1']

并且想使用列表中项目的索引位置对下面的字典进行排序

列表项是键。

dic = {'G_Exis': 'abc', 'fca': '210Y', 'Red_Exis': 107, 'fc_add': '999 Des ST.'} 

我需要最终排序的字典如下所示:

fin_dic = {'fca': '210Y', 'fc_add': '999 Des ST.', 'Red_Exis': 107, 'G_Exis': 'abc'}

提前致谢。

【问题讨论】:

    标签: python list sorting dictionary


    【解决方案1】:

    Dict 不保持秩序,使用collections.OrderedDict:

    from collections import OrderedDict
    od = OrderedDict()
    
    for item in li:
        if item in dic:
            od[item] = dic[item]
    print od
    
    OrderedDict([('fca', '210Y'), ('fc_add', '999 Des ST.'), ('Red_Exis', 107),
                 ('G_Exis', 'abc')])
    

    或作为单行者:

    OrderedDict(sorted(dic.items(), key=lambda t: li.index(t[0])))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多