CodexBloom - Programming Q&A Platform

Python - Sorting a List of Dictionaries by Nested Key with Conditional Logic

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-25
python sorting dictionaries Python

I've searched everywhere and can't find a clear answer... I've been banging my head against this for hours. I'm trying to sort a list of dictionaries in Python based on a nested key that requires conditional logic. I have a list of employee records where each record is a dictionary containing 'name', 'age', and 'details', and 'details' itself is a dictionary with keys 'department' and 'salary'. I need to sort these records primarily by 'department' and then by 'salary', but only include those records where 'salary' is above 50000. Here's my current list: ```python employees = [ {'name': 'Alice', 'age': 30, 'details': {'department': 'HR', 'salary': 60000}}, {'name': 'Bob', 'age': 25, 'details': {'department': 'IT', 'salary': 45000}}, {'name': 'Charlie', 'age': 35, 'details': {'department': 'IT', 'salary': 75000}}, {'name': 'Diana', 'age': 28, 'details': {'department': 'HR', 'salary': 55000}}, {'name': 'Eve', 'age': 22, 'details': {'department': 'Finance', 'salary': 70000}}, ] ``` I want the result to be sorted by department first and, among those in the same department, sorted by salary in descending order, while filtering out those with a salary less than or equal to 50000. I tried using the built-in `sorted()` function with a custom key but I'm struggling with the conditional filtering. Here's what I attempted: ```python sorted_employees = sorted( [emp for emp in employees if emp['details']['salary'] > 50000], key=lambda x: (x['details']['department'], -x['details']['salary']) ) ``` However, this doesn't seem to work as expected. The output is grouped by department, but the salaries aren't sorted correctly within each department. I ended up with: ```python [ {'name': 'Alice', ...}, {'name': 'Diana', ...}, {'name': 'Charlie', ...}, {'name': 'Eve', ...} ] ``` It appears like salaries are not being sorted in descending order. Can anyone help clarify what I'm doing wrong? My development environment is macOS. How would you solve this? My development environment is Windows.