📜  Python – 列映射元组到字典项

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

Python – 列映射元组到字典项

给定长度为 2 的元组矩阵,将每一列的元素值映射到下一列并构造字典键。

方法#1:使用循环

这是可以执行此任务的方式之一。在此,我们迭代所有元素及其下一列元素并构造字典键值对。

Python3
# Python3 code to demonstrate working of 
# Column Mapped Tuples to dictionary items
# Using loop
  
# initializing list
test_list = [[(5, 6), (7, 4), (1, 2)], 
             [(7, 3), (10, 14), (11, 22)] ]
  
# printing original list
print("The original list : " + str(test_list))
  
res = dict()
  
# loop for tuple lists
for idx in range(len(test_list) - 1):
    for idx2 in range(len(test_list[idx])):
          
        # column wise dictionary pairing 
        res[test_list[idx][idx2][0]] = test_list[idx + 1][idx2][0]
        res[test_list[idx][idx2][1]] = test_list[idx + 1][idx2][1]
          
# printing result 
print("The constructed dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Column Mapped Tuples to dictionary items
# Using dictionary comprehension + zip()
  
# initializing list
test_list = [[(5, 6), (7, 4), (1, 2)], 
             [(7, 3), (10, 14), (11, 22)] ]
  
# printing original list
print("The original list : " + str(test_list))
  
# nested dictionary comprehension to form pairing 
# paired using zip()
res = {key[idx] : val[idx] for key, val in zip(
         *tuple(test_list)) for idx in range(len(key))}
          
# printing result 
print("The constructed dictionary : " + str(res))


输出

方法 #2:使用字典理解 + zip()

上述功能的组合提供了一条线来解决这个问题。在此,我们使用 zip() 执行压缩所有列的任务,字典理解用于键值对。

Python3

# Python3 code to demonstrate working of 
# Column Mapped Tuples to dictionary items
# Using dictionary comprehension + zip()
  
# initializing list
test_list = [[(5, 6), (7, 4), (1, 2)], 
             [(7, 3), (10, 14), (11, 22)] ]
  
# printing original list
print("The original list : " + str(test_list))
  
# nested dictionary comprehension to form pairing 
# paired using zip()
res = {key[idx] : val[idx] for key, val in zip(
         *tuple(test_list)) for idx in range(len(key))}
          
# printing result 
print("The constructed dictionary : " + str(res))
输出