Python – 从其他键中过滤键的值
有时,在使用Python字典时,我们可能会遇到一个问题,即我们需要根据其他一些键相等性从键的字典列表中提取一个值。这种问题在包含数据的领域中很常见,例如 Web 开发。让我们讨论可以执行此任务的某些方式。
Input :
test_list = [{‘gfg’ : 5, ‘is’ : 8, ‘best’ : 24}, {‘gfg’ : 7, ‘is’ : 12, ‘best’ : 24}]
req_key = ‘gfg’ [ Requested Key ]
fil_key = ‘best’ [ Filtering Key ]
fil_val = 24 [ Filtering value to be checked ]
Output : [5, 7]
Input :
test_list = [{‘gfg’ : 5, ‘is’ : 8, ‘best’ : 24}]
req_key = ‘gfg’ [ Requested Key ]
fil_key = ‘best’ [ Filtering Key ]
fil_val = 24 [ Filtering value to be checked ]
Output : [5]
方法#1:使用循环
这是解决此问题的蛮力方法。在此,我们手动迭代整个列表并检查过滤键的值,在相等时我们提取所需键的值。
# Python3 code to demonstrate working of
# Filter key's value from other key
# Using loop
# initializing list
test_list = [{'gfg' : 5, 'is' : 8, 'best' : 12},
{'gfg' : 7, 'is' : 12, 'best' : 24},
{'gfg' : 20, 'is' : 17, 'best' : 18}]
# printing original list
print("The original list is : " + str(test_list))
# initializing required key
req_key = 'gfg'
# initializing filter key
fil_key = 'best'
# initializing filter val
fil_val = 24
# Filter key's value from other key
# Using loop
res = []
for sub in test_list:
if sub[fil_key] == fil_val:
res.append(sub[req_key])
# printing result
print("The required value : " + str(res))
The original list is : [{‘gfg’: 5, ‘is’: 8, ‘best’: 12}, {‘gfg’: 7, ‘is’: 12, ‘best’: 24}, {‘gfg’: 20, ‘is’: 17, ‘best’: 18}]
The required value : [7]
方法#2:使用列表推导
这是解决此问题的另一种方法。在此,我们使用列表理解结构以简写方式执行与上述方法类似的任务。
# Python3 code to demonstrate working of
# Filter key's value from other key
# Using list comprehension
# initializing list
test_list = [{'gfg' : 5, 'is' : 8, 'best' : 12},
{'gfg' : 7, 'is' : 12, 'best' : 24},
{'gfg' : 20, 'is' : 17, 'best' : 18}]
# printing original list
print("The original list is : " + str(test_list))
# initializing required key
req_key = 'gfg'
# initializing filter key
fil_key = 'best'
# initializing filter val
fil_val = 24
# Filter key's value from other key
# Using list comprehension
res = [sub[req_key] for sub in test_list if sub[fil_key] == fil_val]
# printing result
print("The required value : " + str(res))
The original list is : [{‘gfg’: 5, ‘is’: 8, ‘best’: 12}, {‘gfg’: 7, ‘is’: 12, ‘best’: 24}, {‘gfg’: 20, ‘is’: 17, ‘best’: 18}]
The required value : [7]