Python – 提取唯一值键对
有时,在处理Python字典时,我们可能会遇到一个问题,即我们需要从字典列表中提取选定的键对,这太独特了。这种问题可以在包括日间编程在内的许多领域中得到应用。让我们讨论可以执行此任务的某些方式。
Input : test_list = [{‘gfg’ : 5, ‘best’ : 12}, {‘gfg’ : 5, ‘best’ : 12}, ]
Output : {(5, 12)}
Input : test_list = [{‘gfg’ : 5, ‘is’: 5, ‘best’ : 12}]
Output : {(5, 12)}
方法#1:使用列表推导
使用上述功能可以解决此问题。在此,我们使用条件和“in”运算符执行匹配。使用列表理解编译的整个逻辑。
# Python3 code to demonstrate working of
# Extract Unique value key pairs
# Using list comprehension
# initializing list
test_list = [{'gfg' : 5, 'is' : 8, 'best' : 12},
{'gfg' : 5, 'is' : 12, 'best' : 12},
{'gfg' : 20, 'is' : 17, 'best' : 12}]
# printing original list
print("The original list is : " + str(test_list))
# initializing required keys
req_key1 = 'gfg'
req_key2 = 'best'
# Extract Unique value key pairs
# Using list comprehension
res = {tuple(sub[idx] for idx in [req_key1, req_key2]) for sub in test_list}
# printing result
print("The required values : " + str(res))
The original list is : [{‘gfg’: 5, ‘is’: 8, ‘best’: 12}, {‘gfg’: 5, ‘is’: 12, ‘best’: 12}, {‘gfg’: 20, ‘is’: 17, ‘best’: 12}]
The required values : {(5, 12), (20, 12)}
方法 #2:使用map() + zip() + itemgetter()
上述功能的组合可用于执行此任务。这里我们使用 itemgetter 来提取值,zip() 用于组合值,map() 用于将组合结果转换为集合。
# Python3 code to demonstrate working of
# Extract Unique value key pairs
# Using map() + zip() + itemgetter()
from operator import itemgetter
# initializing list
test_list = [{'gfg' : 5, 'is' : 8, 'best' : 12},
{'gfg' : 5, 'is' : 12, 'best' : 12},
{'gfg' : 15, 'is' : 17, 'best' : 21}]
# printing original list
print("The original list is : " + str(test_list))
# initializing required keys
req_key1 = 'gfg'
req_key2 = 'best'
# Extract Unique value key pairs
# Using map() + zip() + itemgetter()
temp = zip(*map(itemgetter(req_key1, req_key2), test_list))
res = list(map(set, temp))
# printing result
print("The required values : " + str(res))
The original list is : [{‘gfg’: 5, ‘is’: 8, ‘best’: 12}, {‘gfg’: 5, ‘is’: 12, ‘best’: 12}, {‘gfg’: 15, ‘is’: 17, ‘best’: 21}]
The required values : [{5, 15}, {12, 21}]