Open In App

Python | Convert tuple to adjacent pair dictionary

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with records, we can have a problem in which we have data and need to convert to key-value dictionary using adjacent elements. This problem can have application in web development domain. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using dict() + dictionary comprehension + slicing The above functionalities can be used to solve this problem. In this, we just slice alternate parts of tuple and assign corresponding values using dictionary comprehension. The result is converted to dictionary using dict(). 

Python3




# Python3 code to demonstrate working of
# Convert tuple to adjacent pair dictionary
# using dict() + dictionary comprehension + slicing
 
# initialize tuple
test_tup = (1, 5, 7, 10, 13, 5)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Convert tuple to adjacent pair dictionary
# using dict() + dictionary comprehension + slicing
res = dict(test_tup[idx : idx + 2] for idx in range(0, len(test_tup), 2))
 
# printing result
print("Dictionary converted tuple : " + str(res))


Output

The original tuple : (1, 5, 7, 10, 13, 5)
Dictionary converted tuple : {1: 5, 7: 10, 13: 5}

  Method #2 : Using dict() + zip() + slicing This performs this task in similar way as above method. The difference is that it uses zip() instead of dictionary comprehension to perform task of pairing key-value pair. 

Python3




# Python3 code to demonstrate working of
# Convert tuple to adjacent pair dictionary
# using dict() + zip() + slicing
 
# initialize tuple
test_tup = (1, 5, 7, 10, 13, 5)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Convert tuple to adjacent pair dictionary
# using dict() + zip() + slicing
res = dict(zip(test_tup[::2], test_tup[1::2]))
 
# printing result
print("Dictionary converted tuple : " + str(res))


Output : 

The original tuple : (1, 5, 7, 10, 13, 5)
Dictionary converted tuple : {1: 5, 13: 5, 7: 10}

Method #3 : Using dict() + zip() + iter()

A possible approach to convert a tuple to an adjacent pair dictionary would be to use the iter() function with the zip() function to iterate through the tuple and pair the elements at the even and odd indices as keys and values.

Python3




#Python3 code to demonstrate working of
#Convert tuple to adjacent pair dictionary
#using dict() + zip() + iter()
 
#initialize tuple
test_tup = (1, 5, 7, 10, 13, 5)
 
#printing original tuple
print("The original tuple : " + str(test_tup))
 
#Convert tuple to adjacent pair dictionary
res = dict(zip(iter(test_tup[::2]), iter(test_tup[1::2])))
 
#printing result
print("Dictionary converted tuple : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original tuple : (1, 5, 7, 10, 13, 5)
Dictionary converted tuple : {1: 5, 7: 10, 13: 5}

This method will have time complexity of O(n) and Auxiliary space of O(n) where n is the size of tuple.

Method#4: Using Recursive method.

In this method, we define a recursive function tuple_to_dict that takes a tuple as input. The base cases for this function are when the tuple is empty or has only one element. In both cases, we return an empty dictionary or a dictionary with the single element and None as its value, respectively. For the recursive case, we create a dictionary with the first element of the tuple as the key and the second element as its value. We then merge this dictionary with the dictionary obtained by calling the tuple_to_dict function recursively on the remaining elements of the tuple. This is done using the unpacking operator **.

Python3




def tuple_to_dict(test_tup):
    if len(test_tup) == 0:
        return {}
    elif len(test_tup) == 1:
        return {test_tup[0]: None}
    else:
        return {test_tup[0]: test_tup[1], **tuple_to_dict(test_tup[2:])}
 
# initialize tuple
test_tup = (1, 5, 7, 10, 13, 5)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Convert tuple to adjacent pair dictionary
# using recursion
res = tuple_to_dict(test_tup)
 
# printing result
print("Dictionary converted tuple : " + str(res))


Output

The original tuple : (1, 5, 7, 10, 13, 5)
Dictionary converted tuple : {1: 5, 7: 10, 13: 5}

 The time complexity of this method is O(n), and Auxiliary space of O(n) where n is the length of the tuple.

Method 5 :  using a for loop and enumerate()

step-by-step approach 

  1. Initialize a tuple test_tup with the values (1, 5, 7, 10, 13, 5).
  2. Print the original tuple test_tup.
  3. Initialize an empty dictionary res to store the adjacent pair elements of the tuple.
  4. Iterate through each element val and its corresponding index i in the tuple test_tup using the enumerate() function.
  5. Check if the index i is even or odd using the modulo operator %.
  6. If the index i is even, then store the element val as the key in the dictionary res and its adjacent element in the tuple test_tup (i.e., the element at index i+1) as its value.
  7. Print the dictionary res containing the adjacent pair elements of the original tuple.

Python3




# Python3 code to demonstrate working of
# Convert tuple to adjacent pair dictionary
# using for loop and enumerate()
 
# initialize tuple
test_tup = (1, 5, 7, 10, 13, 5)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Convert tuple to adjacent pair dictionary
# using for loop and enumerate()
res = {}
for i, val in enumerate(test_tup):
    if i % 2 == 0:
        res[val] = test_tup[i+1]
 
# printing result
print("Dictionary converted tuple : " + str(res))


Output

The original tuple : (1, 5, 7, 10, 13, 5)
Dictionary converted tuple : {1: 5, 7: 10, 13: 5}

Time complexity: O(n)
Auxiliary space: O(n/2) (since we’re only storing half of the elements in the tuple as keys in the dictionary)



Last Updated : 23 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads