Python | Filter Tuple Dictionary Keys
Last Updated :
08 May, 2023
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 filtered 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 filtered key’s elements into a list.
Python3
# Python3 code to demonstrate working of
# Filter Tuple Dictionary Keys
# 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))
# Initializing K
K = 5
# Filter Tuple Dictionary Keys
# Using list comprehension
res = [ele for key in test_dict for ele in key if ele > K]
# printing result
print("The filtered dictionary tuple key elements are : " + str(res))
Output : The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
The filtered dictionary tuple key elements are : [6, 9, 10, 8]
Time complexity: O(nm), where n is the number of keys in the dictionary and m is the maximum number of elements in a tuple key.
Auxiliary Space: O(m), where m is the maximum number of elements in a tuple key, for storing the filtered tuple elements in the result list.
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 and then perform the filter operation.
Python3
# Python3 code to demonstrate working of
# Filter Tuple Dictionary Keys
# 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))
# Initializing K
K = 5
# Filter Tuple Dictionary Keys
# Using chain.from_iterable()
temp = list(chain.from_iterable(test_dict))
res = [ele for ele in temp if ele > K]
# printing result
print("The filtered dictionary tuple key elements are : " + str(res))
Output : The original dict is : {(5, 6): 'gfg', (9, 10): 'best', (1, 2, 8): 'is'}
The filtered dictionary tuple key elements are : [6, 9, 10, 8]
Time complexity: O(nm), where n is the number of keys in the dictionary and m is the maximum number of elements in a tuple key.
Auxiliary Space: O(m), where m is the maximum number of elements in a tuple key, for storing the filtered tuple elements in the result list.
Method #3 : Using keys(),extend(),list() methods
Approach
- Convert the keys of dictionary to single list using for loop + extend(),keys(),list() methods and store in x
- Extract elements greater than K and store in res
- Display res
Python3
# Python3 code to demonstrate working of
# Filter Tuple Dictionary Keys
# 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))
# Initializing K
K = 5
x=[]
# Filter Tuple Dictionary Keys
for i in list(test_dict.keys()):
x.extend(list(i))
res=[]
for i in x:
if(i>K):
res.append(i)
# printing result
print("The filtered dictionary tuple key elements are : " + str(res))
OutputThe original dict is : {(5, 6): 'gfg', (1, 2, 8): 'is', (9, 10): 'best'}
The filtered dictionary tuple key elements are : [6, 8, 9, 10]
Time complexity: O(nm), where n is the number of keys in the dictionary and m is the maximum number of elements in a tuple key.
Auxiliary Space: O(m), where m is the maximum number of elements in a tuple key, for storing the filtered tuple elements in the result list.
Similar Reads
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Get all Tuple Keys from Dictionary - Python
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
3 min read
Python - Iterate over Tuples in Dictionary
In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print
2 min read
Unpacking Dictionary Keys into Tuple - Python
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 key
2 min read
Python - Filter Non-None dictionary Keys
Many times, while working with dictionaries, we wish to get keys for a non-null keys. This finds application in Machine Learning in which we have to feed data with no none values. Letâs discuss certain ways in which this task can be performed. Method #1 : Using loop In this we just run a loop for al
6 min read
Unique Dictionary Filter in List - Python
We are given a dictionary in list we need to find unique dictionary. For example, a = [ {"a": 1, "b": 2}, {"a": 1, "b": 2}, {"c": 3}, {"a": 1, "b": 3}] so that output should be [{'a': 1, 'b': 2}, {'a': 1, 'b': 3}, {'c': 3}].Using set with frozensetUsing set with frozenset, we convert dictionary item
3 min read
Get Total Keys in Dictionary - Python
We are given a dictionary and our task is to count the total number of keys in it. For example, consider the dictionary: data = {"a": 1, "b": 2, "c": 3, "d": 4} then the output will be 4 as the total number of keys in this dictionary is 4.Using len() with dictThe simplest way to count the total numb
2 min read
Python - Remove Disjoint Tuple Keys from Dictionary
We are given a dictionary we need to remove the Disjoint Tuple key from it. For example we are given a dictionary d = {('a', 'b'): 1, ('c',): 2, ('d', 'e'): 3, 'f': 4} we need to remove all the disjoint tuple so that the output should be { }. We can use multiple methods like dictionary comprehension
3 min read
Python | Test if key exists in tuple keys dictionary
Sometimes, while working with dictionary data, we need to check if a particular key is present in the dictionary. If keys are elementary, the solution to a problem in discussed and easier to solve. But sometimes, we can have a tuple as key of the dictionary. Let's discuss certain ways in which this
7 min read
Get Dictionary Value by Key - Python
We are given a dictionary and our task is to retrieve the value associated with a given key. However, if the key is not present in the dictionary we need to handle this gracefully to avoid errors. For example, consider the dictionary : d = {'name': 'Alice', 'age': 25, 'city': 'New York'} if we try t
3 min read