![]() |
VOOZH | about |
In Python, dictionaries can have tuples as keys which is useful when we need to store grouped values as a single key. Suppose we have a dictionary where the keys are tuples and we need to extract all the individual elements from these tuple keys into a list. For example, consider the dictionary : d = {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'} here the keys are (5, 6), (9, 10), and (1, 2, 8) and our task is to retrieve all the elements from these tuples into a single list: [5, 6, 9, 10, 1, 2, 8].
In this method we can use itertools.chain.from_iterable() to flatten the tuple keys directly into a list.
[5, 6, 9, 10, 1, 2, 8]
Explanation:
This method offers a memory-efficient way of flattening the tuple keys as the generator expression generates the keys on the fly and chain() combines them into a single list without the need to create multiple intermediate lists.
[5, 6, 9, 10, 1, 2, 8]
Explanation:
This method is simple and intuitive as it uses a loop to go through each tuple key in the dictionary and extend() function to add the elements of each tuple to a list . while it’s easy to understand it involves more overhead due to the multiple function calls within the loop.
[5, 6, 9, 10, 1, 2, 8]
Explanation:
This method is straightforward and simple to understand as it uses sum() to combine the elements of the tuples into one list but it’s less efficient for large datasets because it repeatedly creates new lists for each tuple.
[5, 6, 9, 10, 1, 2, 8]
Explanation: