如何根据数字值对列表字典进行排序?

时间:2017-12-11 22:36:18

标签: python python-3.x list sorting dictionary

我有一个字典作为以下数据结构:

d = {'TRANSFERRED': [2281, 1031, 1775, 867, 1242], # sum gives 7196 
     'CLOSED':      [239, 269, 645, 540, 388], # sum gives 2081
     'DEFERRED':    [89, 5, 68, 48, 37], # sum gives 247
     'IN PROGRESS': [0, 2, 4, 0, 5], # sum gives 11
     'OPEN':        [3, 0, 2, 1, 0], # sum gives 6 
     'QUEUED':      [0, 0, 0, 0, 0]} # sum gives 0

字典包含带有数值的列表,我想根据其数值的总和对它们进行排序,如下所示:

d2 = {'TRANSFERRED': [-2281],
      'CLOSED':      [239], 
      'DEFERRED':    [489],
      'OPEN':        [34],
      'IN PROGRESS': [0],
      'QUEUED':      [-10]}

sorted(d2.items(), key=lambda x: x[1], reverse=True)

如您所见,新词典根据每个列表中从最高到最低的数值之和进行排序。我一直在使用以下技巧来订购包含单个项目的列表,例如:

Awk

我想复制相同的结果,但是要根据字典中每个列表的值的总和。我怎样才能达到这个目标?请随意使用以下链接repl.it - sort dictionary based on its values of lists。欢迎提出反馈或评论来改进这个问题。

2 个答案:

答案 0 :(得分:3)

您只需对当前方法进行一次更改 - 从sum函数返回key

sorted(d2.items(), key=lambda x: sum(x[1]), reverse=True)
#                                ^change ^

演示:

In [2]: sorted(d.items(), key=lambda item: sum(item[1]), reverse=True)
Out[2]: 
[('TRANSFERRED', [2281, 1031, 1775, 867, 1242]),
 ('CLOSED', [239, 269, 645, 540, 388]),
 ('DEFERRED', [89, 5, 68, 48, 37]),
 ('IN PROGRESS', [0, 2, 4, 0, 5]),
 ('OPEN', [3, 0, 2, 1, 0]),
 ('QUEUED', [0, 0, 0, 0, 0])]

答案 1 :(得分:1)

#you can solve this problem using sort and sum functions.


# original list.
d = {'TRANSFERRED': [2281, 1031, 1775, 867, 1242],
     'CLOSED':      [239, 269, 645, 540, 388], 
     'DEFERRED':    [89, 5, 68, 48, 37],
     'OPEN':        [3, 0, 2, 1, 0],
     'IN PROGRESS': [0, 2, 4, 0, 5],
     'QUEUED':      [0, 0, 0, 0, 0]}


#function to calculate the sum of a list
def list_sum(t):
  return sum(t[1])

# we can not sort dict. directly so we have to make the dict into list of tuples
# were key will be the first element and value will be the second element.
# will become 'TRANSFERRED': [2281, 1031, 1775, 867, 1242]
# ( 'TRANSFERRED', [2281, 1031, 1775, 867, 1242])
# t0 = 'TRANSFERRED'
# t1 = [2281, 1031, 1775, 867, 1242]


# sorted function will sorted the list of tuples based on the result
# generated by the list_sum function 

result = sorted(d.items(),key=list_sum,reverse=True)
print(result)