【问题标题】:Is there any way to sort this dictionaries by lowest value from keys?有没有办法按键中的最小值对字典进行排序?
【发布时间】:2019-08-22 11:08:56
【问题描述】:

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

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}

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

【问题讨论】:

    标签: python list sorting dictionary split


    【解决方案1】:

    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 函数的结果进行排序。

    【讨论】:

      【解决方案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}]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-20
        • 2017-08-02
        • 2020-12-09
        • 1970-01-01
        • 2015-04-06
        • 2019-11-21
        • 2011-07-08
        • 1970-01-01
        相关资源
        最近更新 更多