-1

you can considered the following list

[{'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}}]

i want to sort the list of dictionary by the key 'location'

Thanks

Humberto Perez
  • 35
  • 1
  • 1
  • 5
  • 2
    `sort` and `sorted` both have a `key` parameter. If you Google you should be able to answer your own question in a minute or so. – John Coleman Mar 20 '17 at 23:16
  • 2
    Possible duplicate of [How do I sort a list of dictionaries by values of the dictionary in Python?](http://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-values-of-the-dictionary-in-python) – Hamms Mar 20 '17 at 23:20

1 Answers1

2

Use the list.sort() method, passing in the appropriate key= parameter. For example:

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

Complete program:

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)
Robᵩ
  • 163,533
  • 20
  • 239
  • 308