
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements