代码之家  ›  专栏  ›  技术社区  ›  Umar.H

按值对词典进行自定义排序

  •  1
  • Umar.H  · 技术社区  · 5 年前

    我有一个简单的字典和一个列表,我想按字典中的值排序。

    data_dict = {'foo' : 'one', 'bar' : 'two', 'foobar' : 'three', 'notinsort' : 'four'}
    
    custom_sort = ['three','one','two'] 
    

    我自己的尝试是用一个自定义键来理解字典:

    {k:v for k,v in sorted(data_dict.items(), key=lambda i : custom_sort.index(i[1]) )}
    

    它将正确地返回 ValueError: 'four' is not in list

    没问题,我可以用lambda中的if-else语句过滤掉它?由于我仍然希望值最初按自定义排序,然后按自然排序。

    {
        k: v
        for k, v in sorted(
            data_dict.items(),
            key=lambda i: custom_sort.index(i[1])
            if [k for k in data_dict.values() if k in custom_sort] 
            else sorted(data_dict.items()),
        )
    }
    

    这会返回相同的ValueError,我尝试过的任何变体都会忽略自定义键,给我一个自然排序。

    我希望上面输入的输出是:

    data_dict = {'foobar' : 'three', 'foo' : 'one', 'bar' : 'two', 'notinsort' : 'four'}
    

    我有以下问题:

    How do I sort a dictionary by value? &安培; Custom Sorting Python Dictionary

    但没能找到答案。

    1 回复  |  直到 5 年前
        1
  •  4
  •   yatu Sayali Sonawane    5 年前

    相反,您可以预先为查找定义字典(减少排序的复杂性),即 O(n log n) ,因为字典查找是 O(1) ). 这适用于python 3.6>字典顺序如下:

    d = {v:k for k,v in enumerate(custom_sort)}
    # {'three': 0, 'one': 1, 'two': 2}
    dict(sorted(data_dict.items(), key=lambda x: d.get(x[1], float('inf'))))
    # {'foobar': 'three', 'foo': 'one', 'bar': 'two', 'notinsort': 'four'}