Convert Nested dictionary to Mapped Tuple in Python


The nested dictionary is a hierarchical data structure where values themselves are called as dictionaries. It allows storing more than one dictionary inside the base dictionary. The mapped tuple is defined by the collection of tuples where individual tuples contain pairing values. By converting one form into another it means to set the changes between key−value pairs into a tuples list. In Python, we have some built−in functions such as isintance(), extend(), append(), and, str() will be used to convert the Nested dictionary to Mapped Tuple.

Syntax

The following syntax is used in the examples-

isintance()

The isinstance() is a built−in function in Python that checks whether the first parameter is a subclass or an instance of the second parameter.

extend() 

The extend() is a built−in method in Python that adds the specified element at the end of the current list.

append()

The append() is a built−in method in Python that accepts one element as an input parameter which add at the end of the given list.

str()

The built−in function str() is defined by converting the parameter value into the form of value.

Using Recursion

In the following example, The program uses a recursive function to manage some built−in functions− extend() and append() which will convert the nested dictionary to mapped tuple.

Example

def dict_mapped_tup(dictionary):
    map_tuple = []
    for key, value in dictionary.items():
        if isinstance(value, dict):
            map_tuple.extend((key, subkey, subvalue) for subkey, subvalue in dict_mapped_tup(value))
        else:
            map_tuple.append((key, value))
    return map_tuple
# Create the nested dictionary
nes_dict = {
    "key 1": "50",
    "key 2": {
        "subkey 1": "10",
        "subkey 2": "20"
    },
    "key 3": "60"
}
# Calling function
mapped_tup = dict_mapped_tup(nes_dict)
print(mapped_tup)

Output

[('key 1', '50'), ('key 2', 'subkey 1', '10'), ('key 2', 'subkey 2', '20'), ('key 3', '60')]

Using Recursive Generator and isinstance()

In the following example, the program uses recursive generator that acts as a regular function, which means the function is calling itself. Then using the built−in function isinstance() it accepts two parameters to check whether the first parameter is a subclass of the second parameter or not.

Example

def dict_mapped_tup(dictionary):
    for key, value in dictionary.items():
        if isinstance(value, dict):
            yield from ((key,) + subkey_value for subkey_value in dict_mapped_tup(value))
        else:
            yield key, value

# Create the nested dictionary
nested_dict = {
    "key1": "100",
    "key2": {
        "subkey1": "200",
        "subkey2": "300",
        "subkey3": "400"
    },
    "key3": "500"
}
# Calling function
map_tuple = list(dict_mapped_tup(nested_dict))
print(map_tuple)

Output

[('key1', '100'), ('key2', 'subkey1', '200'), ('key2', 'subkey2', '300'), ('key2', 'subkey3', '400'), ('key3', '500')]

Using Dictionary Operation

In the following example, the program uses dictionary operation with the help of a list, tuple, and for loop that iterates through the given list to convert the nested dictionary into mapped tuple.

Example

# Create the nested dictionary
my_dict = {'Tutorials' : {'x' : 10, 'y' : 20}, 'is' : {'x' : 100, 'y' : 400}, 'good' : {'x' : 80, 'y' : 63}}
# Display the original dictionary
print("Original Dictionary: " + str(my_dict))
# Using dictionary operation
result = [(key, tuple(my_dict[k][key] for k in my_dict)) for key in my_dict['Tutorials']]
# Display the output
print("The Combined dictionary: " + str(result))

Output

Original Dictionary: {'Tutorials': {'x': 10, 'y': 20}, 'is': {'x': 100, 'y': 400}, 'good': {'x': 80, 'y': 63}}
The Combined dictionary: [('x', (10, 100, 80)), ('y', (20, 400, 63))]

Conclusion

We discussed the various ways to solve this problem statement. The above two examples use the recursive function which means the function calls itself whereas the third example shows the dictionary operation with the help of list and tuple. This type of code helps to build the logic based on data arrangement.

Updated on: 14-Aug-2023

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements