Open In App

Python – Convert Nested dictionary to Mapped Tuple

Last Updated : 22 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

The task is to convert a nested dictionary into a mapping where each key’s values are transformed into tuples. This involves taking the inner dictionaries and creating tuples for each key-value pair across the nested structure. If a key appears in multiple inner dictionaries, its values should be grouped together in a tuple.

For example, given the nested dictionary d = {‘gfg’: {‘x’: 5, ‘y’: 6}, ‘is’: {‘x’: 1, ‘y’: 4}, ‘best’: {‘x’: 8, ‘y’: 3}},the goal is to convert it into a dictionary where each key is associated with a tuple of values:{‘x’: (5, 1, 8), ‘y’: (6, 4, 3)}.

Using defaultdict

defaultdict from the collections module allows us to easily manage missing keys and assign default values and making it a great choice for converting nested dictionaries to tuples. In this approach, each key’s values are appended to a tuple and efficiently handling the insertion of data without requiring any checks for key existence.

from collections import defaultdict

d = {'gfg': {'x': 5, 'y': 6}, 'is': {'x': 1, 'y': 4}, 'best': {'x': 8, 'y': 3}}

res = defaultdict(tuple) # Creating a defaultdict

# Iterate over the dictionary 'd'
for key, val in d.items():
  
    for ele in val:#  Iterate over the dictionary 'val' 
        res[ele] += (val[ele],)

print(str(list(res.items())))

Output
[('x', (5, 1, 8)), ('y', (6, 4, 3))]

Explanation:

  • res[ele] += (val[ele],): This appends the value from the inner dictionary (val[ele]) to the tuple for the corresponding key (ele) in res.

Using counter

Counter is a subclass of dict designed to count and aggregate values. It can also be utilized to map nested dictionary values into tuples, where values are summed or stored in tuple form.

from collections import Counter

d = {'gfg': {'x': 5, 'y': 6}, 'is': {'x': 1, 'y': 4}, 'best': {'x': 8, 'y': 3}}

res = Counter()   # Initialize `res` to store tuples

for key, val in d.items():
    for ele in val:
        if ele not in res:
            res[ele] = ()  # Initialize with an empty tuple if the key does not exist
        res[ele] += (val[ele],)  # Append the value to the tuple

print(str(list(res.items())))

Output
[('x', (5, 1, 8)), ('y', (6, 4, 3))]

Explanation:

  • (for key, val in d.items()) iterates through the outer dictionary d, where key is the outer key and val is the corresponding inner dictionary.
  • (for ele in val) iterates over the keys in each inner dictionary .
  • if ele not in res checks if the key ele exists in the res Counter. If not, it initializes it with an empty tuple.
  • res[ele] += (val[ele],)This appends the value corresponding to ele from the inner dictionary to its tuple in res.

Using dictionery comprehension

Dictionary comprehension allows us to directly map each key to a tuple without needing additional loops . This approach is Pythonic, making it ideal for situations where we want an efficient and clean solution.

d = {'gfg': {'x': 5, 'y': 6}, 'is': {'x': 1, 'y': 4}, 'best': {'x': 8, 'y': 3}}

res = {ele: tuple(val[ele] for val in d.values()) for ele in next(iter(d.values())).keys()}

print(str(list(res.items())))

Output
[('x', (5, 1, 8)), ('y', (6, 4, 3))]

Explanation:

  • next(iter(d.values())) retrieves the first inner dictionary to access its keys .
  • for ele in next(iter(d.values())).keys() iterates through the keys of the first inner dictionary (‘x’, ‘y’).
  • tuple(val[ele] for val in d.values()): For each key, collects the values from all inner dictionaries and groups them into a tuple.

Using itertools.chain

itertools.chain flatten multiple iterators into a single sequence. This method is ideal when dealing with deeply nested dictionaries and requires flattening the inner dictionary values into tuples. This avoids creating intermediate lists and making it a more memory-efficient choice for flattening and mapping the values.

from itertools import chain

d = {'gfg': {'x': 5, 'y': 6}, 'is': {'x': 1, 'y': 4}, 'best': {'x': 8, 'y': 3}}

res = {}  # Create an empty dictionary

# Iterate over the keys of the first inner dictionary
for ele in next(iter(d.values())).keys():
  
    res[ele] = tuple(chain.from_iterable((val[ele],) for val in d.values()))
print(str(list(res.items())))

Output
[('x', (5, 1, 8)), ('y', (6, 4, 3))]

Explanation:

  • next(iter(d.values())) retrieves the first inner dictionary to get its keys (‘x’, ‘y’).
  • chain.from_iterable((val[ele],) for val in d.values()): For each key (‘x’ or ‘y’), this flattens the values from each inner dictionary into a single iterable and then collects them into a tuple.
  • tuple() converts the flattened values into a tuple.


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg