Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert tuple to adjacent pair dictionary in Python
When it is required to convert a tuple to an adjacent pair dictionary, the dict() method, dictionary comprehension, and slicing can be used.
A dictionary stores values in the form of a (key, value) pair. Dictionary comprehension is a shorthand to iterate through sequences and create dictionaries efficiently.
Slicing extracts elements from an iterable using [start:end] notation, where it includes the start index but excludes the end index.
Using Dictionary Comprehension with Slicing
This method creates pairs by taking every two consecutive elements from the tuple ?
my_tuple = (7, 8, 3, 4, 3, 2)
print("The tuple is:")
print(my_tuple)
result = dict(my_tuple[idx : idx + 2] for idx in range(0, len(my_tuple), 2))
print("The dictionary after converting to adjacent pairs:")
print(result)
The tuple is:
(7, 8, 3, 4, 3, 2)
The dictionary after converting to adjacent pairs:
{7: 8, 3: 2}
Using zip() Method
The zip() function pairs elements from two sequences. We can use slicing to create two sequences ?
my_tuple = (7, 8, 3, 4, 3, 2)
print("The tuple is:")
print(my_tuple)
# Pair elements at even indices with elements at odd indices
result = dict(zip(my_tuple[::2], my_tuple[1::2]))
print("The dictionary using zip():")
print(result)
The tuple is:
(7, 8, 3, 4, 3, 2)
The dictionary using zip():
{7: 8, 3: 4, 3: 2}
Handling Odd Length Tuples
When the tuple has an odd number of elements, the last element won't have a pair ?
my_tuple = (1, 2, 3, 4, 5)
print("The tuple is:")
print(my_tuple)
result = dict(my_tuple[idx : idx + 2] for idx in range(0, len(my_tuple), 2))
print("The dictionary with odd length tuple:")
print(result)
The tuple is:
(1, 2, 3, 4, 5)
The dictionary with odd length tuple:
{1: 2, 3: 4}
Comparison
| Method | Code Complexity | Best For |
|---|---|---|
| Dictionary comprehension | Medium | Custom pairing logic |
zip() with slicing |
Simple | Clean readable code |
Conclusion
Use zip() with slicing for clean readable code when converting tuples to adjacent pair dictionaries. Dictionary comprehension offers more flexibility for custom pairing requirements.
