Table of Contents
Introduction
The task is to convert the given elements into proper key dictionary form i.e. assigning each element to some identifying name.
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:
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:
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