Convert Nested Tuple to Custom Key Dictionary Python (original) (raw)

Given a nested tuple, the task is to convert each inner tuple into a dictionary with predefined custom keys. Each tuple represents a structured record, and the goal is to map every element of the tuple to the appropriate key.

**For example,

**Input: ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10))
**Output: [{'key': 4, 'value': 'Gfg', 'id': 10}, {'key': 3, 'value': 'is', 'id': 8}, {'key': 6, 'value': 'Best', 'id': 10}].

Let’s explore different methods to achieve this conversion.

Using dict() with zip()

This method combines keys and values using the zip() function and then converts them directly into a dictionary using dict().

Python `

a = ((4, 'Gfg', 10), (3, 'is', 8), (6, 'Best', 10)) keys = ['key', 'value', 'id'] res = [dict(zip(keys, sub)) for sub in a] print(res)

`

Output

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

**Explanation:

Using List Comprehension

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

Python `

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:

Using map() with lambda

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.

Python `

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:

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.

Python `

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: