Python | Convert tuple to adjacent pair dictionary

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().

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :



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

 

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.