Convert Nested dictionary to Mapped Tuple in Python

A nested dictionary is a hierarchical data structure where values themselves are dictionaries. Converting nested dictionaries to mapped tuples means transforming key-value pairs into a list of tuples that preserve the hierarchical relationships.

Understanding the Conversion

When converting nested dictionaries to mapped tuples, we flatten the structure while maintaining parent-child relationships. For example:

# Original nested dictionary
nested_dict = {
    "a": 1,
    "b": {
        "c": 2,
        "d": 3
    }
}

# Becomes mapped tuples
# [("a", 1), ("b", "c", 2), ("b", "d", 3)]

Method 1: Using Recursion with List Operations

This approach uses a recursive function with isinstance() to check for nested dictionaries and extend() to add tuples ?

def dict_to_mapped_tuple(dictionary):
    mapped_tuples = []
    for key, value in dictionary.items():
        if isinstance(value, dict):
            # Recursively process nested dictionaries
            mapped_tuples.extend((key, subkey, subvalue) for subkey, subvalue in dict_to_mapped_tuple(value))
        else:
            # Add simple key-value as tuple
            mapped_tuples.append((key, value))
    return mapped_tuples

# Example nested dictionary
nested_dict = {
    "name": "John",
    "details": {
        "age": 25,
        "city": "New York"
    },
    "score": 95
}

# Convert to mapped tuples
result = dict_to_mapped_tuple(nested_dict)
print(result)
[('name', 'John'), ('details', 'age', 25), ('details', 'city', 'New York'), ('score', 95)]

Method 2: Using Generator with yield

This memory-efficient approach uses a generator function that yields tuples as they are created ?

def dict_to_mapped_tuple_gen(dictionary):
    for key, value in dictionary.items():
        if isinstance(value, dict):
            # Use yield from to recursively yield tuples
            yield from ((key,) + subtuple for subtuple in dict_to_mapped_tuple_gen(value))
        else:
            yield (key, value)

# Example nested dictionary
nested_dict = {
    "product": "laptop",
    "specs": {
        "ram": "8GB",
        "storage": "256GB",
        "processor": "Intel i5"
    },
    "price": 850
}

# Convert to mapped tuples using generator
result = list(dict_to_mapped_tuple_gen(nested_dict))
print(result)
[('product', 'laptop'), ('specs', 'ram', '8GB'), ('specs', 'storage', '256GB'), ('specs', 'processor', 'Intel i5'), ('price', 850)]

Method 3: Dictionary Comprehension for Specific Structure

For dictionaries with uniform nested structure, you can use list comprehension ?

# Dictionary with uniform nested structure
score_dict = {
    'math': {'john': 90, 'jane': 85}, 
    'science': {'john': 88, 'jane': 92}, 
    'english': {'john': 95, 'jane': 89}
}

print("Original Dictionary:", score_dict)

# Convert to mapped tuples grouping by student
result = [(student, tuple(score_dict[subject][student] for subject in score_dict)) 
          for student in score_dict['math']]

print("Mapped Tuples:", result)
Original Dictionary: {'math': {'john': 90, 'jane': 85}, 'science': {'john': 88, 'jane': 92}, 'english': {'john': 95, 'jane': 89}}
Mapped Tuples: [('john', (90, 88, 95)), ('jane', (85, 92, 89))]

Comparison of Methods

Method Memory Usage Best For Flexibility
Recursive List Higher Simple nested structures High
Generator Lower Large datasets High
Comprehension Medium Uniform structures Limited

Conclusion

Converting nested dictionaries to mapped tuples helps flatten hierarchical data while preserving relationships. Use generators for memory efficiency, recursion for flexibility, and comprehensions for uniform structures.

Updated on: 2026-03-27T12:17:02+05:30

631 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements