Open In App

Convert Nested Tuple to Custom Key Dictionary – Python

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

The task is to convert a nested tuple into a dictionary with custom keys. Each tuple in the nested structure contains multiple elements, and the goal is to map these elements to specific keys in a dictionary.

For example, given the tuple a = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10)), the goal is to convert each inner tuple into a dictionary with keys 'key', 'value', and 'id' that correspond to the elements of the tuple. After conversion, the result will be [{‘key’: 4, ‘value’: ‘Gfg’, ‘id’: 10}, {‘key’: 3, ‘value’: ‘is’, ‘id’: 8}, {‘key’: 6, ‘value’: ‘Best’, ‘id’: 10}].

Using list comprehension

List comprehension is the most efficient method as it avoids unnecessary function calls and offering a readable solution. It creates a new list by iterating over the tuples and directly converting them to dictionaries with custom keys.

a = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))

res = [{'key': sub[0], 'value': sub[1], 'id': sub[2]} for sub in a]
print(str(res))

Output
[{'key': 4, 'value': 'Gfg', 'id': 10}, {'key': 3, 'value': 'is', 'id': 8}, {'key': 6, 'value': 'Best', 'id': 10}]

Explanation: List Comprehension create a new list of dictionaries res and each dictionary corresponds to an inner tuple sub from the original tuple a.

Using map()

map() function applies a function to each item in a list one by one. It processes the items quickly because it doesn’t create intermediate lists, which makes it faster than a traditional for loop.

a = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))

res = list(map(lambda sub: {'key': sub[0], 'value': sub[1], 'id': sub[2]}, a))
print(str(res))

Output
[{'key': 4, 'value': 'Gfg', 'id': 10}, {'key': 3, 'value': 'is', 'id': 8}, {'key': 6, 'value': 'Best', 'id': 10}]

Explanation:

  • map() : This function applies the lambda function to each element in the iterable a.
  • lambda(): This takes each sub and returns a dictionary with the keys 'key', 'value', and 'id', which correspond to the first, second, and third elements of sub, respectively.

Table of Content

Using for loop

for loop is less efficient than list comprehension but offers more flexibility for complex transformations and additional logic when needed. It’s ideal when performance isn’t the main concern.

a = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))

res = []
for sub in a:
    res.append({'key': sub[0], 'value': sub[1], 'id': sub[2]})

print(str(res))

Output
[{'key': 4, 'value': 'Gfg', 'id': 10}, {'key': 3, 'value': 'is', 'id': 8}, {'key': 6, 'value': 'Best', 'id': 10}]

Explanation:

  • for loop: This iterates over each tuple in a and for each tuple and dictionary is created with custom keys.
  • dictionaries are appended to the list res, which is then printed.


Next Article

Similar Reads

three90RightbarBannerImg