-3

I have a list which I have gotten from json.loads();

myList = [{'label': 'Users', 'host': 'XYZ', 'tags': {'customer': 'XYZ'}, 'data': [[1518756360, 1]]}, 
          {'label': 'Users', 'host': 'ABC', 'tags': {'customer': 'ABC'}, 'data': [[1518756360, 1]]}, 
          {'label': 'Users', 'host': 'EFG', 'tags': {'customer': 'EFG'}, 'data': [[1518756360, 1]]}] 

Is there a way to sort this list based of host key so that it becomes like this?

mySortedList = [{'label': 'Users', 'host': 'ABC', 'tags': {'customer': 'ABC'}, 'data': [[1518756360, 1]]}, 
                {'label': 'Users', 'host': 'EFG', 'tags': {'customer': 'EFG'}, 'data': [[1518756360, 1]]}, 
                {'label': 'Users', 'host': 'XYZ', 'tags': {'customer': 'XYZ'}, 'data': [[1518756360, 1]]}] 

I tried myList.sort() and myList.sort(key='host') but it didn't work.

melpomene
  • 84,125
  • 8
  • 85
  • 148
nadir781
  • 3
  • 3

1 Answers1

0

With sorted you can determine after what you want to sort with a lambda function. In your case sorted(myList, key=lambda k: k['host']).

Or without lambda (as pointed out by @padraic-cunningham and @arount):

from operator import itemgetter
sorted(myList, key=itemgetter('host'))
fdelia
  • 385
  • 9
  • 18
  • 1
    No lambda needed here. As @padraic-cunningham pointed in comments you can just specify what key you want to use as sorting index – Arount Feb 16 '18 at 08:18