GoCoding.org

Program to convert nested tuple to custom key dictionary using Python

by | Jul 4, 2021 | Python Programs

Introduction

The task is to convert the given elements into proper key dictionary form i.e. assigning each element to some identifying name.

Program to convert nested tuple to custom key dictionary using Python

Program

Approach 1

ip_tuple = ((1, 'Ram'), (2, 'Sita'))
print("The given tuple is: "+ str(ip_tuple))
k = ['id', 'name']


# Using zip() and list comprehension
output = [{k: ele for k, ele in zip(k, sub)} for sub in ip_tuple]
print("The converted dictionary is : " + str(output))

Output:

Program to convert nested tuple to custom key dictionary using Python Output 1

Approach 2

ip_tuple = ((5, 'Goa', 9), (2, 'UK', 7))
print("The given tuple is: "+ str(ip_tuple))


# Using list comprehension and dictionary comprehension
output = [{'id': sub[0], 'name': sub[1]} for sub in ip_tuple]
print("The converted dictionary is : " + str(output))

Output:

Program to convert nested tuple to custom key dictionary using Python Output 2

Explanation

Approach 1: In this approach we have used list comprehension with dictionary comprehension. The keys are assigned with the help of dictionary comprehension whereas the data construction is done by providing suitable condition to list comprehension.

Approach 2: In second approach we have used zip() method in list comprehension. The list comprehension condition assign the keys and zip() methods maps the keys to values. The advantage of using zip() is it provides the flexibility of predefining keys.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.