📜  Python|将元组转换为相邻对字典

📅  最后修改于: 2022-05-13 01:55:32.447000             🧑  作者: Mango

Python|将元组转换为相邻对字典

有时,在处理记录时,我们可能会遇到一个问题,即我们有数据并且需要使用相邻元素转换为键值字典。这个问题可以在 web 开发领域有应用。让我们讨论可以执行此任务的某些方式。

方法 #1:使用dict() + 字典理解 + 切片
上述功能可用于解决此问题。在这种情况下,我们只是对元组的替代部分进行切片,并使用字典理解分配相应的值。使用dict()将结果转换为字典。

# 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))
输出 :
The original tuple : (1, 5, 7, 10, 13, 5)
Dictionary converted tuple : {1: 5, 13: 5, 7: 10}

方法 #2:使用dict() + zip() + 切片
这以与上述方法类似的方式执行此任务。不同之处在于它使用zip()而不是字典理解来执行配对键值对的任务。

# 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))
输出 :
The original tuple : (1, 5, 7, 10, 13, 5)
Dictionary converted tuple : {1: 5, 13: 5, 7: 10}