简体   繁体   中英

Sort list of dicts by sub-key value

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.

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}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM