Filter key from Nested item using Python

Python can extract specific values from complex data structures containing nested dictionaries or lists by filtering keys from nested items. This technique is essential for data manipulation, API response processing, and configuration parsing where you need to work with specific parts of complex data structures.

Key Methods

The following built-in methods are commonly used for filtering nested data ?

isinstance()

Checks whether an object is an instance of a specific class or type ?

data = {"name": "John"}
print(isinstance(data, dict))
print(isinstance([1, 2, 3], list))
True
True

items()

Returns key-value pairs from a dictionary ?

data = {"a": 1, "b": 2}
for key, value in data.items():
    print(f"{key}: {value}")
a: 1
b: 2

Using Recursive Function

The recursive approach uses isinstance() to check data types and processes nested structures by calling itself ?

def filter_keys_nested(data, target_keys):
    if isinstance(data, dict):
        return {k: filter_keys_nested(v, target_keys) for k, v in data.items() if k in target_keys}
    elif isinstance(data, list):
        return [filter_keys_nested(item, target_keys) for item in data]
    else:
        return data

# Create nested data structure
nested_data = {
    "name": "John",
    "details": {
        "age": 30,
        "city": "New York"
    },
    "hobbies": [
        {"hobby": "reading"},
        {"hobby": "swimming"}
    ]
}

filtered_result = filter_keys_nested(nested_data, ["details", "city", "hobby"])
print(filtered_result)
{'details': {'city': 'New York'}, 'hobbies': [{'hobby': 'reading'}, {'hobby': 'swimming'}]}

Using Stack-Based Approach

This iterative approach uses a stack to traverse nested structures without recursion ?

def filter_keys_stack(data, target_keys):
    def filter_dict(d):
        result = {}
        for k, v in d.items():
            if k in target_keys:
                if isinstance(v, dict):
                    result[k] = filter_dict(v)
                elif isinstance(v, list):
                    result[k] = [filter_dict(item) if isinstance(item, dict) else item for item in v]
                else:
                    result[k] = v
        return result
    
    return filter_dict(data) if isinstance(data, dict) else data

# Create nested data structure  
nested_data = {
    "name": "John",
    "profile": {
        "age": 25,
        "location": "Boston"
    },
    "skills": [
        {"skill": "Python", "level": "Advanced"},
        {"skill": "Java", "level": "Intermediate"}
    ]
}

filtered_result = filter_keys_stack(nested_data, ["profile", "location", "skills", "skill"])
print(filtered_result)
{'profile': {'location': 'Boston'}, 'skills': [{'skill': 'Python'}, {'skill': 'Java'}]}

Using Dictionary Comprehension

A simpler approach for filtering keys at specific nested levels ?

def filter_nested_simple(data, target_keys):
    if isinstance(data, dict):
        filtered = {}
        for key, value in data.items():
            if key in target_keys:
                if isinstance(value, (dict, list)):
                    filtered[key] = filter_nested_simple(value, target_keys)
                else:
                    filtered[key] = value
        return filtered
    elif isinstance(data, list):
        return [filter_nested_simple(item, target_keys) for item in data]
    return data

# Example with employee data
employee_data = {
    "id": 123,
    "personal": {
        "name": "Alice",
        "email": "alice@email.com"
    },
    "projects": [
        {"title": "Web App", "status": "Active"},
        {"title": "Mobile App", "status": "Complete"}
    ]
}

result = filter_nested_simple(employee_data, ["personal", "name", "projects", "title"])
print(result)
{'personal': {'name': 'Alice'}, 'projects': [{'title': 'Web App'}, {'title': 'Mobile App'}]}

Comparison

Method Complexity Best For Memory Usage
Recursive Function Medium Deep nesting High (call stack)
Stack-Based High Large datasets Medium
Dictionary Comprehension Low Simple filtering Low

Conclusion

Filtering keys from nested data structures is essential for data processing and API handling. Use recursive functions for deep nesting, stack-based approaches for large datasets, and dictionary comprehension for simple filtering tasks.

Updated on: 2026-03-27T12:22:28+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements