📜  Python| Key 值大于 K 的记录

📅  最后修改于: 2022-05-13 01:55:06.909000             🧑  作者: Mango

Python| Key 值大于 K 的记录

当一个人开始使用字典时,获取具有至少相应键值的合适字典的问题是很常见的。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是可以执行此任务的蛮力方法。为此,我们只使用简单的检查和比较并附加具有特定键值大于 K 的记录。

# Python3 code to demonstrate working of
# Records with Key's value greater than K
# Using loop
  
# Initialize list
test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6}, 
            {'it' : 5, 'is' : 7, 'best' : 8},
            {'CS' : 10, 'is' : 8, 'best' : 10}]
  
# Printing original list
print("The original list is : " + str(test_list))
  
# Initialize K 
K = 6
  
# Using loop
# Records with Key's value greater than K
res = []
for sub in test_list:
    if sub['is'] >= K:
        res.append(sub)
  
# printing result 
print("The filtered dictionary records is : " + str(res))
输出 :
The original list is : [{'best': 6, 'gfg': 2, 'is': 4}, {'best': 8, 'it': 5, 'is': 7}, {'best': 10, 'CS': 10, 'is': 8}]
The filtered dictionary records is : [{'best': 8, 'it': 5, 'is': 7}, {'best': 10, 'CS': 10, 'is': 8}]

方法 #2:使用list() + 字典理解
这些方法的组合也可用于执行此任务。这种区别在于它是单行且更高效,因为列表函数使用迭代器作为内部实现,这比泛型方法更快。

# Python3 code to demonstrate working of
# Find dictionary matching value in list
# Using list() + dictionary comprehension
  
# Initialize list
test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6}, 
            {'it' : 5, 'is' : 7, 'best' : 8},
            {'CS' : 10, 'is' : 8, 'best' : 10}]
  
# Printing original list
print("The original list is : " + str(test_list))
  
# Initialize K 
K = 6
  
# Using list() + dictionary comprehension
# Find dictionary matching value in list
res = list((sub for sub in test_list if sub['is'] >= K))
  
# printing result 
print("The filtered dictionary records : " + str(res))
输出 :
The original list is : [{'best': 6, 'gfg': 2, 'is': 4}, {'best': 8, 'it': 5, 'is': 7}, {'best': 10, 'CS': 10, 'is': 8}]
The filtered dictionary records is : [{'best': 8, 'it': 5, 'is': 7}, {'best': 10, 'CS': 10, 'is': 8}]