📜  Python|将字典键解包到元组中

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

Python|将字典键解包到元组中

在某些情况下,我们可能会遇到需要将字典键解包为元组的问题。这种问题可能发生在我们只关心字典的键并希望拥有它的元组的情况下。让我们讨论可以执行此任务的某些方式。

方法 #1:使用tuple()

将字典简单类型转换为元组实际上完成了所需的任务。此函数仅获取键并根据需要将它们转换为键元组。

# Python3 code to demonstrate working of
# Unpacking dictionary keys into tuple
# Using tuple()
  
# initializing dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using tuple()
# Unpacking dictionary keys into tuple
res = tuple(test_dict)
  
# printing result
print("The unpacked dict. keys into tuple is :  " + str(res))
输出 :
The original dictionary is : {'best': 3, 'is': 2, 'Gfg': 1}
The unpacked dict. keys into tuple is :  ('best', 'is', 'Gfg')

方法#2:使用"=" operator和多个变量
此方法也可用于执行此特定任务。在此,我们将逗号分隔的变量分配给字典。我们使用与字典中的键一样多的变量。在未知或很多键的情况下不建议使用此方法。

# Python3 code to demonstrate working of
# Unpacking dictionary keys into tuple
# Using "=" operator and multiple variables
  
# initializing dictionary
test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Using "=" operator and multiple variables
# Unpacking dictionary keys into tuple
a, b, c = test_dict
res = a, b, c
  
# printing result
print("The unpacked dict. keys into tuple is :  " + str(res))
输出 :
The original dictionary is : {'best': 3, 'is': 2, 'Gfg': 1}
The unpacked dict. keys into tuple is :  ('best', 'is', 'Gfg')