如何使用多个数值列表对字典进行排序?

时间:2017-12-11 19:51:29

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

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

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]}

字典包含带有数值的列表,我想从最低到最高值排序,如下所示:

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

我担心字典无法排序,因为它们本身就是无序的,但其他类型如列表和元组不是无序的,而且,我一直在使用以下技巧来为包含单个项目的列表命令字典,例如: / p>

d2 = {'TRANSFERRED': [-2281],
      'CLOSED':      [239], 
      'DEFERRED':    [489],
      'OPEN':        [34],
      'IN PROGRESS': [0],
      'QUEUED':      [-10]}
sorted(d2.items(), key=lambda x: x[1], reverse=True)

结果给出了以下排序数据结构:

[('DEFERRED', [489]), 
 ('CLOSED', [239]), 
 ('OPEN', [34]), 
 ('IN PROGRESS', [0]), 
 ('QUEUED', [-10]), 
 ('TRANSFERRED', [-2281])]

我希望复制相同的结果,但是使用包含多个数值列表的字典。我怎样才能做到这一点?请随时使用以下链接repl.it - sort dictionary with lists of multiple items来测试您的搜索结果。欢迎提出反馈或评论来改进这个问题。

2 个答案:

答案 0 :(得分:2)

您可以使用dict.items()

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]}
new_d = {a:sorted(b) for a, b in d.items()}

输出:

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

答案 1 :(得分:0)

d = {
     'TRANSFERRED':2281,
     'CLOSED':239, 
     'DEFERRED':89,
     'OPEN':3,
     'IN PROGRESS':2,
     'QUEUED':0
}

# Some usefull method of dictionary
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
#
# To get dict keys:
# ----------------
#
# d.keys() = > dict_keys(['TRANSFERRED', 'CLOSED', 'DEFERRED', 'OPEN', 'IN PROGRESS', 'QUEUED'])
# The output is an iterable.
#
# To get dict values
#-------------------
#
# d.values() => dict_values([2281, 239, 89, 3, 2, 0])
# The out is an iterable.
#
# To get both key and values
# --------------------------
#
# d.items() => dict_items([('TRANSFERRED', 2281), ('CLOSED', 239), ('DEFERRED', 89), ('OPEN', 3),
# ('IN PROGRESS', 2), ('QUEUED', 0)])
# The out is iterable of tuples. Each tuple contains key as the first tuple item and value as
# second item. (k,v)