Parse a JSON array of people with json.loads and reshape it into a name→age dict with a comprehension. Everyday data transformation, tested in Python.
The problem
json_text is a JSON array of objects with "name" and "age". Return a dict mapping each name to its age.
Examples
Example 1
Input
name_to_age('[{"name": "John", "age": 30}, {"name": "Alice", "age": 25}]')Expected output
{'John': 30, 'Alice': 25}
+ 2 hidden tests on Submit — later duplicate wins.
Edge cases to ask about
- Empty array
- Duplicate names
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| json.loads + dict comprehension | O(n) | O(n) |
Walkthrough of the optimal approach (try it yourself first)
json.loads turns the text into a list of dicts; a comprehension reshapes it. Know the loads/load (string vs file) and dumps/dump pairs.
Mention what you would ask: duplicate names (last wins here), missing keys (p.get("age")), and validation with pydantic for anything coming from outside.
Complexity: O(n) time, O(n) space. Parsing and the comprehension are both linear in the size of the input.
Reveal the reference solution
import json def name_to_age(json_text): people = json.loads(json_text) return {p["name"]: p["age"] for p in people}
Follow-ups interviewers ask
- Group names by age instead.
- Validate the input schema.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Transform JSON Data in Python?
The optimal solution runs in O(n) time and O(n) auxiliary space. Parsing and the comprehension are both linear in the size of the input.
What follow-up questions do interviewers ask about Transform JSON Data in Python?
Group names by age instead. Validate the input schema.
