How to Flatten a Dictionary into a List of Tuples

86 views

How to Flatten a Dictionary into a List of Tuples

How to Flatten a Dictionary into a List of Tuples

I have a nested dictionary and I need to flatten it into a list of tuples. How can I accomplish this?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

You can use a recursive function to traverse the dictionary and collect key-value pairs into a list of tuples.

Code Example:

def flatten_dict(d, parent_key='', result=None):
    if result is None:
        result = []
    for key, value in d.items():
        new_key = f"{parent_key}.{key}" if parent_key else key
        if isinstance(value, dict):
            flatten_dict(value, new_key, result)
        else:
            result.append((new_key, value))
    return result

nested_dict = {
    "a": 1,
    "b": {
        "c": 2,
        "d": {
            "e": 3
        }
    }
}

print(flatten_dict(nested_dict))


This function recursively traverses the dictionary, flattening nested structures, and returns a list of tuples where each tuple represents a key-value pair.

solveurit24@gmail.com Changed status to publish February 16, 2025
0