Python|在列表中查找字典匹配值
当开始使用字典时,仅获取具有相应键的特定值的合适字典的问题是很常见的。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方法。为此,我们只需使用简单的检查和比较并在找到合适的匹配项后返回结果,并为其余的字典打断。
# Python3 code to demonstrate working of
# Find dictionary matching value in list
# Using loop
# Initialize list
test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6},
{'it' : 5, 'is' : 7, 'best' : 8},
{'CS' : 10}]
# Printing original list
print("The original list is : " + str(test_list))
# Using loop
# Find dictionary matching value in list
res = None
for sub in test_list:
if sub['is'] == 7:
res = sub
break
# printing result
print("The filtered dictionary value is : " + str(res))
输出 :
The original list is : [{'is': 4, 'gfg': 2, 'best': 6}, {'is': 7, 'best': 8, 'it': 5}, {'CS': 10}]
The filtered dictionary value is : {'is': 7, 'best': 8, 'it': 5}
方法 #2:使用next()
+ 字典理解
这些方法的组合也可用于执行此任务。这个区别在于它是一个单行且更高效,因为下一个函数使用迭代器作为内部实现,这比泛型方法更快。
# Python3 code to demonstrate working of
# Find dictionary matching value in list
# Using next() + dictionary comprehension
# Initialize list
test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6},
{'it' : 5, 'is' : 7, 'best' : 8},
{'CS' : 10}]
# Printing original list
print("The original list is : " + str(test_list))
# Using next() + dictionary comprehension
# Find dictionary matching value in list
res = next((sub for sub in test_list if sub['is'] == 7), None)
# printing result
print("The filtered dictionary value is : " + str(res))
输出 :
The original list is : [{'is': 4, 'gfg': 2, 'best': 6}, {'is': 7, 'best': 8, 'it': 5}, {'CS': 10}]
The filtered dictionary value is : {'is': 7, 'best': 8, 'it': 5}