The task is to unpack the keys of a dictionary into a tuple. This involves extracting the keys of the dictionary and storing them in a tuple, which is an immutable sequence.
For example, given the dictionary d = {'Gfg': 1, 'is': 2, 'best': 3}, the goal is to convert it into a tuple containing the keys like ('Gfg', 'is', 'best').
Using tuple()
The simplest method to convert dictionary keys into a tuple is using the built-in tuple() function. This method directly converts the keys view into a tuple.
d= {'Gfg': 1, 'is': 2, 'best': 3}
res = tuple(d.keys())
print(str(res))
Output
('Gfg', 'is', 'best')
Explanation:
d.keys()returns the keysdict_keys(['Gfg', 'is', 'best']).tuple(d.keys())converts it to('Gfg', 'is', 'best').str(res)converts the tuple to the string"(Gfg, is, best)".
Table of Content
Using * operator
* operator can be used to unpack dictionary keys directly into a tuple. This is a unique method and can be very useful when we need to pass dictionary keys as arguments to other functions or manipulate them.
d= {'Gfg': 1, 'is': 2, 'best': 3}
res = (*d.keys(),)
print(str(res))
Output
('Gfg', 'is', 'best')
Explanation:
(*d.keys(),):Thisunpacks the keys into the tuple('Gfg', 'is', 'best').str(res):Thisconverts it to the string"(Gfg, is, best)".
Using list comprehension
List comprehension can be used to extract dictionary keys and then convert them into a tuple. This approach gives more flexibility in terms of applying conditions or transformations on the keys.
d= {'Gfg': 1, 'is': 2, 'best': 3}
res = tuple([key for key in d])
print(str(res))
Output
('Gfg', 'is', 'best')
Explanation:
[key for key in d]:Thiscreates the list['Gfg', 'is', 'best'].tuple([...]):Thisconverts it to the tuple('Gfg', 'is', 'best').str(res):Thisconverts it to the string"(Gfg, is, best)".
Using map()
map() function can be used to convert dictionary keys into a tuple. While this method is less common for this specific task, it provides a functional approach to unpacking.
d = {'Gfg': 1, 'is': 2, 'best': 3}
res = tuple(map(str, d.keys()))
print(str(res))
Output
('Gfg', 'is', 'best')
Explanation:
- map(str, d.keys()) converts each key to a string.
- tuple(...) converts the mapped result to a tuple ('Gfg', 'is', 'best').
- str(res) converts it to the string "(Gfg, is, best)".