如何对具有多个数值列表的字典进行排序? [英] how to sort a dictionary with lists of multiple numeric values?

查看:130
本文介绍了如何对具有多个数值列表的字典进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,其数据结构如下:

I have a dictionary as the following data structure:

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

字典包含带有数字值的列表,我想按从最小到最大的顺序对它们进行排序,如下所示:

The dictionary contains lists with numeric values and I would like to order them from the lowest to the highest value, something like this:

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

我担心不能对字典进行排序,因为它们本质上是无序的,但是其他类型(例如列表和元组)不是无序的,而且,我一直在使用以下技巧来对包含单个项目的列表进行字典排序:

I am concerned that dictionaries cannot be sorted because they are inherently orderless but other types such as lists and tuples are not orderless, moreover, I have been using the following trick to order dictionaries with lists that contain single items such as:

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

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

The result gives the following sorted data structure:

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

我想复制相同的结果,但要使用包含多个数值列表的字典.我怎样才能做到这一点?请随时使用以下链接 repl.it-对包含多个项目列表的字典进行排序进行测试您的结果.欢迎提供反馈或意见以改善此问题.

I want to replicate this same result but with a dictionary with lists of multiple numeric values. How can I achieve this? Please, feel free to use the following link repl.it - sort dictionary with lists of multiple items to test your results. Feedback or comments to improve this question are welcome.

推荐答案

您可以使用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]}

这篇关于如何对具有多个数值列表的字典进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆