2017-03-20 24 views
-1

你可以考虑以下列表我如何排序python嵌套的口述列表?

[{'mesa': {'url': 'https://anongit.freedesktop.org/git/mesa/mesa.git', 'commit': 'a6e212440278df2bb0766a5cf745935d94809144', 'location': 2}}, {'macros': {'url': 'https://anongit.freedesktop.org/git/xorg/util/macros.git', 'commit': '39f07f7db58ebbf3dcb64a2bf9098ed5cf3d1223', 'location': 7}}, {'drm': {'url': 'https://anongit.freedesktop.org/git/mesa/drm.git', 'commit': '19c4cfc54918d361f2535aec16650e9f0be667cd', 'location': 1}}] 

我想排序字典由关键“位置”

感谢

+2

'sort'和'sorted'都有一个'key'参数。如果你是谷歌,你应该能够在一分钟左右回答你自己的问题。 –

+2

可能的重复[如何通过Python中的字典值对字典列表进行排序?](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries -by-the-values-of-the-dictionary-in-python) – Hamms

回答

2

使用list.sort()方法列表中,通过在适当的key=参数。例如:

l.sort(key=lambda x: list(x.values())[0]['location']) 

完整的程序:

from pprint import pprint 
l=[{'mesa': {'url': 'https://anongit.freedesktop.org/git/mesa/mesa.git', 'commit': 'a6e212440278df2bb0766a5cf745935d94809144', 'location': 2}}, {'macros': {'url': 'https://anongit.freedesktop.org/git/xorg/util/macros.git', 'commit': '39f07f7db58ebbf3dcb64a2bf9098ed5cf3d1223', 'location': 7}}, {'drm': {'url': 'https://anongit.freedesktop.org/git/mesa/drm.git', 'commit': '19c4cfc54918d361f2535aec16650e9f0be667cd', 'location': 1}}] 

l.sort(key=lambda x: list(x.values())[0]['location']) 
pprint(l) 
+0

是的,这对我很有用,非常感谢 –