-1

I have a list of dicts of dicts like this:

mydic = [{'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}},{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}]

How do I sort it by locname? I should get this:

mydic_sorted = [{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}, {'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}}]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
user3241376
  • 407
  • 7
  • 20

1 Answers1

4

You can by using a lambda function as a key argument to the function

>>> mydic = [{'name':'a', 'loc':{'locname':'z'}, 'id':{'value':'1'}},{'name':'b', 'loc':{'locname':'o'}, 'id':{'value':'2'}}]
>>> sorted(mydic,key = lambda x:x['loc']['locname'])
[{'loc': {'locname': 'o'}, 'name': 'b', 'id': {'value': '2'}}, {'loc': {'locname': 'z'}, 'name': 'a', 'id': {'value': '1'}}]

Ref: The docs

sorted(iterable[, cmp[, key[, reverse]]])

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140