Unpacking Dictionary keys into Tuple using Tuple()
The simple type casting of a dictionary into a tuple in fact does the required task. This function takes just the keys and converts them into key tuples as required.
Python3
# 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.keys()) # printing result print ( "The unpacked dict. keys into tuple is : " + str (res)) |
Output
The original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3}
The unpacked dict. keys into tuple is : ('Gfg', 'is', 'best')
Time complexity: O(1). This is because the program performs a constant number of operations to create a tuple from the keys of the dictionary. The time required to create the tuple is independent of the size of the input dictionary.
Auxiliary space: O(k), where k is the number of keys in the input dictionary.
Python | Unpacking dictionary keys into tuple
In certain cases, we might come into a problem in which we require to unpack dictionary keys to tuples. This kind of problem can occur in cases we are just concerned about the keys of dictionaries and wish to have a tuple of them. Letβs discuss certain ways in which this task can be performed in Python.
Example
Input: {'Welcome': 1, 'to': 2, 'GFG': 3}
Output: ('Welcome', 'to', 'GFG')
Explanation: In this, we are unpacking the keys of Dictionary into Tuple in Python.