Sort List of Dicts Practice Problem
This data science coding problem helps you practice Sorting & Searching, sort list of dicts, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Sorting & Searching.
- Problem ID: 104
- Problem key: 104-sort-list-of-dicts
- URL: https://datacrack.app/solve/104-sort-list-of-dicts
- Difficulty: easy
- Topic: Sorting & Searching
- Module: Python Fundamentals
Problem Statement
# 🧩 Sort List of Dicts
---
### 🎯 Goal
Sorting a list of records by a specific field is one of the most common data manipulation tasks. This problem teaches Python's `sorted()` with the `key` parameter — the same mechanism that powers `df.sort_values()` in Pandas.
---
### 🔍 The `key` Parameter
Python's `sorted()` accepts a `key` function that extracts a comparison value from each element:
```python
sorted(records, key=lambda r: r["score"], reverse=True)
```
---
### 💻 Task
Implement `sort_records(records, key, descending)` using Python's `sorted()`.
---
### 📥 Input
- `records`: list of dicts — each dict has the same set of keys
- `key`: string — the field to sort by
- `descending`: bool — if `True`, sort largest first; if `False`, sort smallest first
### 📤 Output
- A new list of the same dicts, sorted by the specified key
---
### 🧩 Starter Code
```python
def sort_records(records, key, descending):
"""
Sort a list of dictionaries by a specified key.
Args:
records (list[dict]): List of records
key (str): The field to sort by
descending (bool): True for descending, False for ascending
Returns:
list[dict]: Sorted list of records
"""
# 🧠 TODO: Use sorted() with a lambda that extracts record[key]
# 🧠 TODO: Pass reverse=descending
pass
```
---
### 💡 Example
```python
records = [{"name": "Charlie", "score": 85}, {"name": "Alice", "score": 92}, {"name": "Bob", "score": 78}]
sort_records(records, "score", descending=True)
# Expected: [{"name": "Alice", "score": 92}, {"name": "Charlie", "score": 85}, {"name": "Bob", "score": 78}]
```
---
### 🔑 Key Concepts
- `sorted(iterable, key=..., reverse=...)` — returns a new sorted list
- `lambda r: r["score"]` — extracts the sort key from each record
- `reverse=True` → descending, `reverse=False` → ascendingStarter Code
def sort_records(records, key, descending):
"""
Sort a list of dictionaries by a specified key.
Args:
records (list[dict]): List of records
key (str): The field to sort by
descending (bool): True for descending, False for ascending
Returns:
list[dict]: Sorted list of records
"""
# 🧠 TODO: Use sorted() with a lambda that extracts record[key]
# 🧠 TODO: Pass reverse=descending
pass