Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Sort a list of dictionaries by a nested value

Use sorted with a lambda key to sort dictionaries by a value nested inside sub-dictionaries.

Python practice16 minFunctions as Objects (Lambda, Map/Filter)IntermediateLast updated March 20, 2026

Problem statement

You are given a list of dictionaries where the value you should sort by is nested inside one or more sub-dictionaries. Implement sort_by_nested(items, keys, reverse=False) that returns a new list sorted by the nested value located by traversing the dictionary using the sequence of keys provided (keys is a list of keys). Assume the path exists for each item and that the values are mutually comparable.

Task

Implement a function that sorts a list of dictionaries by a value found at a provided nested key path.

Examples

Sort by nested numeric score

Input

sort_by_nested([{'name':'alice','stats':{'score':10}},{'name':'bob','stats':{'score':5}}], ['stats','score'])

Output

[{'name': 'bob', 'stats': {'score': 5}}, {'name': 'alice', 'stats': {'score': 10}}]

Sort ascending by stats->score

Input format

A list of dictionaries and a list of keys describing the nested path, e.g. keys=['stats','score']. Optionally a boolean reverse argument.

Output format

A new list of dictionaries sorted by the nested value.

Constraints

The nested key path exists for every dictionary and the target values are comparable (e.g., all numbers or all strings).

Samples

Sample 1

Input

sort_by_nested([{'id':1,'meta':{'info':{'rank':2}}},{'id':2,'meta':{'info':{'rank':1}}}], ['meta','info','rank'])

Output

[{'id': 2, 'meta': {'info': {'rank': 1}}}, {'id': 1, 'meta': {'info': {'rank': 2}}}]

Sorted by deeper nested rank