Python / Core Python Fundamentals Interview Questions
How do you work with nested data structures such as a list of dictionaries?
A list of dictionaries is the most common Python pattern for representing structured data from APIs, CSV rows, database query results, and JSON payloads. Each dictionary is one record; the list is the collection.
employees = [ {'name': 'Alice', 'dept': 'Engineering', 'salary': 95000}, {'name': 'Bob', 'dept': 'Marketing', 'salary': 72000}, {'name': 'Carol', 'dept': 'Engineering', 'salary': 105000}, {'name': 'Dave', 'dept': 'Marketing', 'salary': 68000}, ] # Filter: Engineering employees eng = [e for e in employees if e['dept'] == 'Engineering'] # Map: extract names only names = [e['name'] for e in employees] # Sort by salary descending ranked = sorted(employees, key=lambda e: e['salary'], reverse=True) # Group by department using defaultdict from collections import defaultdict by_dept = defaultdict(list) for emp in employees: by_dept[emp['dept']].append(emp['name']) # {'Engineering': ['Alice', 'Carol'], 'Marketing': ['Bob', 'Dave']} # Average salary per department dept_salary = {} for dept, members in by_dept.items(): salaries = [e['salary'] for e in employees if e['name'] in members] dept_salary[dept] = sum(salaries) / len(salaries)
When accessing nested values that may not exist, chain .get() calls or use a library like glom for deeply nested paths. Safe access pattern: record.get('address', {}).get('city', 'Unknown').
More Related questions...