📜  Python|元组键字典转换

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

Python|元组键字典转换

在Python中编码时总是需要相互转换,这也是因为Python作为数据科学领域的主要语言的扩展。本文讨论了另一个问题,它转换为字典并将键作为第一对元素分配为元组,其余作为它的值。让我们讨论可以执行此操作的某些方式。

方法#1:使用字典理解
这个问题可以使用字典理解的简写来解决,它执行字典内单行循环的经典 Naive 方法。

# Python3 code to demonstrate
# Tuple key dictionary conversion
# using list comprehension
  
# initializing list
test_list = [('Nikhil', 21, 'JIIT'), ('Akash', 22, 'JIIT'), ('Akshat', 22, 'JIIT')]
  
# printing original list
print("The original list : " + str(test_list))
  
# using list comprehension
# Tuple key dictionary conversion
res = {(sub[0], sub[1]): sub[2:] for sub in test_list}
  
# print result
print("The dictionary after conversion : " + str(res))
输出 :
The original list : [('Nikhil', 21, 'JIIT'), ('Akash', 22, 'JIIT'), ('Akshat', 22, 'JIIT')]
The dictionary after conversion : {('Akash', 22): ('JIIT', ), ('Akshat', 22): ('JIIT', ), ('Nikhil', 21): ('JIIT', )}

方法 #2:使用dict() + 字典理解
执行与上述方法类似的任务,不同之处在于创建字典的方式。在上述方法中,字典是使用理解创建的,这里 dict函数用于创建字典。

# Python3 code to demonstrate
# Tuple key dictionary conversion
# using dict() + dictionary comprehension
  
# initializing list
test_list = [('Nikhil', 21, 'JIIT'), ('Akash', 22, 'JIIT'), ('Akshat', 22, 'JIIT')]
  
# printing original list
print("The original list : " + str(test_list))
  
# using dict() + dictionary comprehension
# Tuple key dictionary conversion
res = dict(((idx[0], idx[1]), idx[2:]) for idx in test_list) 
  
# print result
print("The dictionary after conversion : " + str(res))
输出 :
The original list : [('Nikhil', 21, 'JIIT'), ('Akash', 22, 'JIIT'), ('Akshat', 22, 'JIIT')]
The dictionary after conversion : {('Akash', 22): ('JIIT', ), ('Akshat', 22): ('JIIT', ), ('Nikhil', 21): ('JIIT', )}