Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Sort Dictionary by Age

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Sort Dictionary by Age. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Accenture España needs a consistently ordered view of staff records for an internal Python utility. Given a dictionary mapping each person's name to their age, return a new dictionary ordered by age from highest to lowest.

Do not modify the original dictionary. If multiple people have the same age, preserve their original insertion order. Python dictionaries preserve insertion order, so the returned dictionary's iteration order represents the required result.

Formal Specification

Implement sort_by_age(people), where:

  1. people is a dictionary with unique string names as keys and integer ages as values.
  2. The function returns a new dictionary containing the same key-value pairs.
  3. Entries are ordered by age in descending order.
  4. Entries with equal ages retain their order from people.
  5. The input dictionary itself must remain unchanged.

Constraints

  • 0 <= len(people) <= 10^5
  • Names are unique non-empty strings
  • 0 <= age <= 150
  • The input dictionary must not be mutated

Function Signature

def sort_by_age(people):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output