如何在python中将字典val与键一起排序

时间:2014-03-20 15:49:21

标签: python sorting dictionary

我有两个字典,我需要将字典中的一个与键和值一起排序。由于没有为字典提供排序,我该如何实现? 考虑一下我要排序的字典:

list1 = [10.0035,12.3243,0.7654,15.2487,2.1222, 7.8768]
list2 = [0,1,2,3,4,5]
dic = {'val': list1, 'key': list2}

所以,当我对它进行排序时,它应该显示为:

>>> dic 
{'key': [2,4,5,0,1,3], 'val':[0.7654,2.1222, 7.8768,10.0035,12.3243,15.2487]}

提前致谢!

2 个答案:

答案 0 :(得分:2)

将值拼接在一起,排序和解压缩:

dic['val'], dic['key'] = zip(*sorted(zip(dic['val'], dic['key'])))

演示:

>>> list1 = [10.0035,12.3243,0.7654,15.2487,2.1222, 7.8768]
>>> list2 = [0,1,2,3,4,5]
>>> dic = {'val': list1, 'key': list2}
>>> dic['val'], dic['key'] = zip(*sorted(zip(dic['val'], dic['key'])))
>>> dic
{'key': (2, 4, 5, 0, 1, 3), 'val': (0.7654, 2.1222, 7.8768, 10.0035, 12.3243, 15.2487)}

这两个列表恰好是字典中的值这一事实并不妨碍它们被排序。

答案 1 :(得分:1)

您可以在创建dict之前对其进行排序,然后创建字典

list1, list2 = [10.0035,12.3243,0.7654,15.2487,2.1222, 7.8768], [0,1,2,3,4,5]
key, val = zip(*sorted(zip(list1, list2)))
print dict(key=key, val=val)
# {'val': (2,4,5,0,1,3), 'key': (0.7654,2.1222,7.8768,10.0035,12.3243,15.2487)}