Convert tuple to adjacent pair dictionary in Python


When it is required to convert a tuple to an adjacency pair dictionary, the 'dict' method, the dictionary comprehension, and slicing can be used.

A dictionary stores values in the form of a (key, value) pair. The dictionary comprehension is a shorthand to iterate through the dictionary and perform operations on it.

Slicing will give the values present in an iterable from a given lower index value to a given higher index value, but excludes the element at the higher index value.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = (7, 8, 3, 4, 3, 2)

print ("The first tuple is : " )
print(my_tuple_1)

my_result = dict(my_tuple_1[idx : idx + 2] for idx in range(0, len(my_tuple_1), 2))

print("The dictionary after converting to tuple is: ")
print(my_result)

Output

The first tuple is :
(7, 8, 3, 4, 3, 2)
The dictionary after converting to tuple is:
{7: 8, 3: 2}

Explanation

  • A tuple is defined and is displayed on the console.
  • The 'dict' method is used to convert the tuple into a dictionary by iterating over the elements in the tuple.
  • This result is assigned to a variable.
  • It is displayed as output on the console.

Updated on: 12-Mar-2021

149 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements