📜  Python – 查找字符串列表中的字典键

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

Python – 查找字符串列表中的字典键

有时,在使用Python字典时,我们可能会遇到需要从输入的字符串列表中提取字典键的问题。这个问题可以应用于包括数据在内的许多领域。让我们讨论可以执行此任务的某些方式。

方法#1:使用列表推导
这是可以执行此任务的蛮力方式。在此,我们使用条件语句在每个字符串中查找与键匹配的字符串,并从字符串列表中提取键。

# Python3 code to demonstrate working of 
# Extract dictionary keys in Strings List
# Using list comprehension
  
# initializing list
test_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing dictionary
test_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10}
  
# Extract dictionary keys in Strings List
# Using list comprehension
res = [ele if len(ele) > 0 else [None] for ele in [[key for key in test_dict if key in sub]
                                       for sub in test_list]]
                                         
# printing result 
print("The matching keys list : " + str(res)) 
输出 :
The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks']
The matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]

方法 #2:使用filter() + lambda + 列表推导
上述功能的组合也可以用来解决这个问题。在此,我们使用 filter() 和 lambda 执行过滤任务,列表理解有助于减少一级嵌套。

# Python3 code to demonstrate working of 
# Extract dictionary keys in Strings List
# Using filter() + lambda + list comprehension
  
# initializing list
test_list = ["GeeksforGeeks is best for geeks", "I love GeeksforGeeks"]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing dictionary
test_dict = {'Geeks' : 5, 'CS' : 6, 'best' : 7, 'love' : 10}
  
# Extract dictionary keys in Strings List
# Using filter() + lambda + list comprehension
res = [list(filter(lambda ele: ele in sub, test_dict)) for sub in test_list]
                                         
# printing result 
print("The matching keys list : " + str(res)) 
输出 :
The original list is : ['GeeksforGeeks is best for geeks', 'I love GeeksforGeeks']
The matching keys list : [['best', 'Geeks'], ['love', 'Geeks']]