使用Lamba对OrderedDict排序

时间:2019-07-17 19:24:18

标签: python sorting lambda ordereddictionary

我必须使用sorted方法和lambda在python中对有序字典进行排序。我按键排序,键是字符串 这是我拥有的字典代码:

sensors = OrderedDict()
sensors['4213'] = ("STEM Center", 0)
sensors['4201'] = ("Foundations Lab ", 1)
sensors['4204'] = ("CS Lab ", 2)
sensors['4218'] = ("Workshop Room ", 3)
sensors['4205'] = ("Tiled Room ", 4)
sensors['Out'] = ("Outside ", 5)

我该如何对它进行排序,以便首先显示4201,然后增加数字,然后显示最后一个,出来?

我尝试实现它以及它的变体,但是它不起作用,元素的顺序保持不变

OrderedDict(sorted(sensors.items(), key=lambda x: x[0])

变化:

-sorted(sensors.items(), key=lambda x: x[0])
-creating a regular dictionary called sensors and then making a new ordered dictionary using OrderedDict(sorted(sensors.items(), key=lambda x: x[0])

谢谢!

1 个答案:

答案 0 :(得分:1)

OrderedDict中的键顺序等于插入顺序。要对其进行排序,请按期望的顺序从头开始创建一个新的

import collections

# source does not have to be sorted, a regular dict will do
sensors = {}
sensors['4213'] = ("STEM Center", 0)
sensors['4201'] = ("Foundations Lab ", 1)
sensors['4204'] = ("CS Lab ", 2)
sensors['4218'] = ("Workshop Room ", 3)
sensors['4205'] = ("Tiled Room ", 4)
sensors['Out'] = ("Outside ", 5)

sorted_keys = sorted(sensors)     # key=... optional
sorted_sensors = collections.OrderedDict((key, sensors[key]) for key in sorted_keys)