Q:

Python program to convert tuple to adjacent pair dictionary

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Converting Tuple to Adjacent pair Dictionary

In this program, we have a tuple consisting of integer values. We need to create a Python program that will convert the tuple to an adjacent pair dictionary.

Input:
(4, 1, 7, 8, 9, 5)

Output:
{4: 1, 7:8, 9:5}

For this, we will treverse the tuple and for each pair, convert it to a key-value pair of a dictionary.

In Python, we have multiple methods to perform this task.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by using the slice method which will slice the tuple to a pair of two elements and convert to a key-value pair dictionary using the dict() method.

# Python program to convert tuple to 
# adjacent pair dictionary

# Initializing and printing tuple
myTuple = (4, 1, 7, 8, 9, 5)
print("The elements of the tuple are " + str(myTuple))

# Converting Tuple to adjacent 
# pair dictionary
adjDict = dict(myTuple[idx : idx + 2] for idx in range(0, len(myTuple), 2))

# Printing result
print("Adjacent pair dictionary created form tuple : " + str(adjDict))

Output:

The elements of the tuple are (4, 1, 7, 8, 9, 5)
Adjacent pair dictionary created form tuple : {4: 1, 7: 8, 9: 5}

Method 2:

Another method to solve the problem is by using the zip() method which will create a dictionary consisting of pairs of key-value.

# Python program to convert tuple to 
# adjacent pair dictionary

# Initializing and printing tuple
myTuple = (4, 1, 7, 8, 9, 5)
print("The elements of the tuple are " + str(myTuple))

# Converting Tuple to Adjacent pair dictionary
adjDict = dict(zip(myTuple[::2], myTuple[1::2]))

# Printing result
print("Adjacent pair dictionary created form tuple : " + str(adjDict))

Output:

The elements of the tuple are (4, 1, 7, 8, 9, 5)
Adjacent pair dictionary created form tuple : {4: 1, 7: 8, 9: 5}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to count all the elements till firs... >>
<< Python program to check for None tuple...