Dat*_*ice 1 python sorting dictionary
我有一个简单的字典和一个列表,我想按字典中的值排序。
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'}
我有以下问题:
如何按值对字典进行排序? & 自定义排序 Python 字典
但无法得到答案。
您可以预先为查找定义一个字典(降低排序的复杂性,即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'}