Python|过滤元组字典键
有时,在使用Python字典时,我们可以使用元组形式的键。一个元组可以包含许多元素,有时,获取它们可能是必不可少的。如果它们是字典键的一部分,并且我们希望获得过滤后的元组键元素,我们需要执行某些功能来实现这一点。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
在这个方法中,我们只是遍历每个字典项并将其过滤的键的元素放入一个列表中。
# 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))
输出 :
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]
方法 #2:使用chain.from_iterable()
该任务可以以更紧凑的形式执行,使用 from_iterable() 使用一个单词而不是一行,它在内部访问元组元素并存储在列表中,然后执行过滤操作。
# 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))
输出 :
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]