有什么方法可以根据键中的最小值对字典进行排序吗?

时间:2019-08-22 11:08:56

标签: python list sorting dictionary split

我只想用输入文件中的一些值对这些词典进行排序。

def sortdicts():
    listofs=[]
    listofs=splitndict()
    print sorted(listofs)

splitndict()函数具有以下输出: [{'a': 1, 'b': 2}, {'c': 2, 'd': 4}, {'a': 7, 'c': 3}, {'y': 5, 'x': 0}]

虽然输入来自另一个文件,但它是:

a 1
b 2

c 2
d 4

a 7
c 3

x 0
y 5

我用它来分割字典:

def splitndict():
    listofd=[]
    variablesRead=readfromfile()
    splitted=[i.split() for i in variablesRead]
    d={}
    for lines in splitted:
        if lines:
            d[lines[0]]=int(lines[1])
        elif d=={}:
            pass
        else:
            listofd.append(d)
            d={}
        print listofd
    return listofd

输出文件应如下所示:

[{'y': 5, 'x': 0}, {'a': 1, 'b': 2}, {'c': 2, 'd': 4}, {'a': 7, 'c': 3}

此输出是因为: 需要按每个字典键中的最小值排序。

2 个答案:

答案 0 :(得分:2)

array = [{'y': 5, 'x': 0}, {'a': 1, 'b': 2}, {'c': 2, 'd': 4}, {'a': 7, 'c': 3}]

上述数组:

array = sorted(array, lambda element: min(element.values()))

其中“ element.values()”返回字典中的所有值,“ min”返回这些值中的最小值。 “ sorted”将lambda函数内部的每个字典(一个元素)一一传递。并根据lambda函数的结果进行排序。

答案 1 :(得分:2)

x = [{'y': 5, 'x': 0}, {'a': 1, 'b': 2}, {'c': 2, 'd': 4}, {'a': 7, 'c': 3}]
sorted(x, key=lambda i: min(i.values()))

输出为

[{'y': 5, 'x': 0}, {'a': 1, 'b': 2}, {'c': 2, 'd': 4}, {'a': 7, 'c': 3}]
相关问题