📜  Python|字典到元组转换列表

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

Python|字典到元组转换列表

数据类型之间的相互转换是一个有许多用例的问题,并且是要解决的更大问题中的常见子问题。元组到字典的转换之前已经讨论过。本文讨论了一种相反的情况,其中将字典转换为元组列表作为表示问题的方式。让我们讨论一些可以解决这个问题的方法。

方法 #1:使用列表理解 + 元组 + items()
这个问题可以通过使用列表推导来构造列表来解决,元组是通过在元组中手动插入键来构造的,并且项目函数用于以元组的形式获取字典的项目键和值。

# Python3 code to demonstrate
# Dictionary to list of tuple conversion
# using list comprehension + tuple + items()
  
# initializing Dictionary
test_dict = {"Nikhil" : (22, "JIIT"), "Akshat" : (21, "JIIT")} 
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# using list comprehension + tuple + items()
# Dictionary to list of tuple conversion
res = [(key, i, j) for key, (i, j) in test_dict.items()]
  
# print result
print("The list after conversion : " + str(res))
输出 :
The original dictionary : {'Nikhil': (22, 'JIIT'), 'Akshat': (21, 'JIIT')}
The list after conversion : [('Nikhil', 22, 'JIIT'), ('Akshat', 21, 'JIIT')]

方法 #2:使用列表推导 + items() + “ + ”运算符
此方法与上述方法类似,但对上述函数进行了修改,并允许该功能添加尽可能多的键,而不是上述方法所允许的限制数量。

# Python3 code to demonstrate
# Dictionary to list of tuple conversion
# using list comprehension + items() + "+" operator
  
# initializing Dictionary
test_dict = {"Nikhil" : (22, "JIIT"), "Akshat" : (21, "JIIT")} 
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# using list comprehension + items() + "+" operator
# Dictionary to list of tuple conversion
res = [(key, ) + val for key, val in test_dict.items()]
  
# print result
print("The list after conversion : " + str(res))
输出 :
The original dictionary : {'Nikhil': (22, 'JIIT'), 'Akshat': (21, 'JIIT')}
The list after conversion : [('Nikhil', 22, 'JIIT'), ('Akshat', 21, 'JIIT')]