Unpacking Dictionary keys into Tuple use the items() Method
We are using the items() method of the dictionary and iterating over it to create the tuple of keys in Python. The dictionary method generates a view object that showcases a list of key-value pairs from the dictionary as tuples. Each tuple comprises a key and its corresponding value. This technique offers an efficient approach to obtaining access to both keys and values at once, making it a useful tool for various data manipulation tasks.
Python3
# initializing dictionary test_dict = { 'Gfg' : 1 , 'is' : 2 , 'best' : 3 } # using items() method to get list of key-value pairs items = test_dict.items() # extracting only keys from each tuple using list comprehension keys = [key for key, value in items] # converting keys list to tuple using tuple() function res = tuple (keys) # printing original dictionary print ( "The original dictionary is : " + str (test_dict)) # printing result print ( "The unpacked dict. keys into tuple is : " + str (res)) |
The original dictionary is : {'Gfg': 1, 'is': 2, 'best': 3} The unpacked dict. keys into tuple is : ('Gfg', 'is', 'best')
Time complexity: O(n) since we need to iterate over all key-value pairs in the dictionary.
Auxiliary space: O(n) as well since we need to create a list to store the keys before converting it to a tuple.
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.