0

I have following list of dictionaries:

test_list = [
        {'sr_no': 1, 'recipe_type': 'Main Dish', 'name': 'Salmon & Brown Rice'}, 
        {'sr_no': 2, 'recipe_type': 'Side Dish', 'name': 'Cupcakes'}, 
        {'sr_no': 3, 'recipe_type': 'Main Dish', 'name': 'Whole chicken'}, 
        {'sr_no': 4, 'recipe_type': 'Desserts', 'name': 'test'}
    ]

I need to sort it on base of name index value alphabetically. As below:

test_list = [
        {'sr_no': 2, 'recipe_type': 'Side Dish', 'name': 'Cupcakes'}, 
        {'sr_no': 1, 'recipe_type': 'Main Dish', 'name': 'Salmon & Brown Rice'}, 
        {'sr_no': 4, 'recipe_type': 'Desserts', 'name': 'test'}
        {'sr_no': 3, 'recipe_type': 'Main Dish', 'name': 'Whole chicken'}, 
    ]

I have searched this on SO and google but find no definite answer.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Always_a_learner
  • 4,585
  • 13
  • 63
  • 112

1 Answers1

2

You can pass key function that returns name from each dict to sorted:

>>> import pprint
>>> test_list = [
...         {'sr_no': 1, 'recipe_type': 'Main Dish', 'name': 'Salmon & Brown Rice'},
...         {'sr_no': 2, 'recipe_type': 'Side Dish', 'name': 'Cupcakes'},
...         {'sr_no': 3, 'recipe_type': 'Main Dish', 'name': 'Whole chicken'},
...         {'sr_no': 4, 'recipe_type': 'Desserts', 'name': 'test'}
...     ]
>>> pprint.pprint(sorted(test_list, key=lambda x: x['name'].lower()))
[{'name': 'Cupcakes', 'recipe_type': 'Side Dish', 'sr_no': 2},
 {'name': 'Salmon & Brown Rice', 'recipe_type': 'Main Dish', 'sr_no': 1},
 {'name': 'test', 'recipe_type': 'Desserts', 'sr_no': 4},
 {'name': 'Whole chicken', 'recipe_type': 'Main Dish', 'sr_no': 3}]
niemmi
  • 17,113
  • 7
  • 35
  • 42
  • thanks but the sorted result is not as required. Name is not sorted alphabetically. Whole chicken should come at last position. – Always_a_learner Jul 23 '16 at 08:25
  • 1
    @Simer Oops, didn't notice you had names starting with upper & lower case. That can be mitigated by converting the name to lower (or upper) case which I've modified the answer to do. – niemmi Jul 23 '16 at 08:30