Open In App

Python | Get all tuple keys from dictionary

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Sometimes, while working with Python dictionaries, we can have it’s keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get all the tuple key elements, we need to perform certain functionalities to achieve this. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using list comprehension In this method, we just iterate through the each dictionary item and get it’s key’s elements into a list. 

Step-by-step approach:

  • The res list is initialized using a list comprehension. The list comprehension iterates over the keys in the test_dict dictionary, and for each key, it iterates over the elements in the key tuple using a nested loop.
  • The ele variable is used to store the current element in the key tuple. The resulting list contains all the elements from all the key tuples in the dictionary.
  • The resulting list res is printed using the print() function and the str() function to convert the list to a string format. The output shows all the elements from all the key tuples in the dictionary.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Get all tuple keys from dictionary
# Using list comprehension
 
# Initializing dict
test_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}
 
# printing original dict
print("The original dict is : " + str(test_dict))
 
# Get all tuple keys from dictionary
# Using list comprehension
res = [ele for key in test_dict for ele in key]
 
# printing result
print("The dictionary tuple key elements are : " + str(res))


Output : 

The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
The dictionary tuple key elements are : [5, 6, 9, 10, 1, 2, 8]

Time complexity: O(n), where n is the total number of elements in all the keys of the input dictionary. This is because the program iterates through all the keys of the dictionary and all the elements of each key, performing a constant-time operation on each element.
Auxiliary space: O(n), where n is the total number of elements in all the keys of the input dictionary. This is because the program creates a list to store the resulting key elements, which can have a maximum length of n. Therefore, the program uses O(n) additional memory to store its data structures.

Method #2: Using chain.from_iterable() This task can be performed in more compact form, using one word instead of one-line by using from_iterable(), which internally accesses the tuple elements and stores in list. 

Python3




# Python3 code to demonstrate working of
# Get all tuple keys from dictionary
# Using chain.from_iterable()
from itertools import chain
 
# Initializing dict
test_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}
 
# printing original dict
print("The original dict is : " + str(test_dict))
 
# Get all tuple keys from dictionary
# Using chain.from_iterable()
res = list(chain.from_iterable(test_dict))
 
# printing result
print("The dictionary tuple key elements are : " + str(res))


Output : 

The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
The dictionary tuple key elements are : [5, 6, 9, 10, 1, 2, 8]

Time complexity: O(N), where N is the number of keys in the dictionary.
Auxiliary Space: O(N), where N is the number of keys in the dictionary. This is because we are creating a list of all the keys in the dictionary, which requires memory proportional to the number of keys.

 Method #3 : Using type(),items(),extend(),list() methods

Python3




# Python3 code to demonstrate working of
# Get all tuple keys from dictionary
 
# Initializing dict
test_dict = {(5, 6): 'gfg',  (9, 10): 'best', (1, 2, 8): 'is'}
 
# printing original dict
print("The original dict is : " + str(test_dict))
 
res = []
for key, value in test_dict.items():
    if type(key) is tuple:
        listTuple = list(key)
        res.extend(listTuple)
# printing result
print("The dictionary tuple key elements are : " + str(res))


Output

The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
The dictionary tuple key elements are : [5, 6, 9, 10, 1, 2, 8]

Time Complexity: O(N*M)
Auxiliary Space: O(N*M)

Method 4:  Using the list() method. 

Get all tuple keys from a dictionary in Python is by using a loop to iterate through the keys of the dictionary and then flatten each tuple key into a list using the list() method. We can then add each element of the flattened list into a new list.

Python3




# Initializing dict
test_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}
 
# printing original dict
print("The original dict is : " + str(test_dict))
 
# Get all tuple keys from dictionary using loop and flatten
res = []
for key in test_dict:
    res.extend(list(key))
 
# printing result
print("The dictionary tuple key elements are : " + str(res))


Output

The original dict is : {(5, 6): 'gfg', (1, 2, 8): 'is', (9, 10): 'best'}
The dictionary tuple key elements are : [5, 6, 1, 2, 8, 9, 10]

Time Complexity: O(N*M)
Auxiliary Space: O(N*M)

Method 5: Using a generator expression and the itertools.chain() method.

  • We first import the itertools module.
  • Then we initialize the dictionary test_dict.
  • Next, we use a generator expression to iterate through each key in test_dict and generate a tuple of its elements.
  • We then use the itertools.chain() method to concatenate all the generated tuples into a single iterable.
  • Finally, we use the list() method to convert the iterable to a list and assign it to the variable res.
  • We then print the result.

Python3




import itertools
 
# Initializing dict
test_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}
 
# printing original dict
print("The original dict is : " + str(test_dict))
 
# Get all tuple keys from dictionary using generator expression and itertools.chain()
res = list(itertools.chain(*(key for key in test_dict)))
 
# printing result
print("The dictionary tuple key elements are : " + str(res))


Output

The original dict is : {(5, 6): 'gfg', (1, 2, 8): 'is', (9, 10): 'best'}
The dictionary tuple key elements are : [5, 6, 1, 2, 8, 9, 10]

Time complexity: O(n), where n is the total number of elements in all the tuple keys of the dictionary. This is because we iterate through each key in the dictionary exactly once and append its elements to the list.
Auxiliary space: O(n), since we create a list res to store all the tuple elements. Additionally, we also create a generator expression and an iterator object using the itertools.chain() method, but these do not take up any significant amount of memory. Therefore, the overall space complexity is also O(n).

Method 6:Using numpy:

 Step-by-step approach :

  • Create a dictionary named test_dict with keys as tuples and values as strings.
  • Print the original dictionary.
  • Use a list comprehension to create a list of individual elements from the dictionary keys.
  • Use reduce() with a lambda function to concatenate the lists of tuple elements into a single list.
  • Convert the list to a numpy array using np.array().
  • Print the resulting numpy array.

Python3




import numpy as np
from functools import reduce
 
# Initializing dict
test_dict = {(5, 6) : 'gfg', (1, 2, 8) : 'is', (9, 10) : 'best'}
 
# printing original dict
print("The original dict is : " + str(test_dict))
 
# Get all tuple keys from dictionary
# Using reduce() and numpy
res = np.array(reduce(lambda x, y: x + y, [list(key) for key in test_dict]))
 
# printing result
print("The dictionary tuple key elements are : " + str(res))
#This code is contributed by Jyothi pinjala


Output:

The original dict is : {(5, 6): 'gfg', (1, 2, 8): 'is', (9, 10): 'best'}
The dictionary tuple key elements are : [ 5  6  1  2  8  9 10]

Time complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), where n is the length of the concatenated list of tuple elements.



Last Updated : 10 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads