Python 查找在字符串列表中存在的字典键
字典是Python的著名数据类型之一,由键值对组成。字符串列表是由单引号或双引号表示的元素集合。在Python中,我们有一些内置函数,例如keys()、set()、intersection和append(),用于查找在字符串列表中存在的字典键。
让我们以一个例子来说明。
有两个可用的集合:
给定的字典,{‘T’: 1, ‘M’: 2, ‘E’: 3, ‘C’: 4}
给定的列表,[T, A, B, P, E, L]
因此,最后的结果变为[T, E]。
语法
以下是示例中使用的语法
keys()
The keys()是Python中的一个内置函数,它返回字典中所有可用键的列表。
set()
set()是Python的内置函数,可用于将多个元素存储到单个变量中。
intersection()
Python的内置函数intersection()可以找到两个不同集合中的共同匹配项。
append()
append()是Python中的内置函数,它将元素插入到列表的末尾。
使用列表推导
在下面的示例中,程序从一个名为dict_keys()的递归函数开始,它接受两个参数d和s,用于从给定的输入字典和字符串dict1和stng中获取值。接下来,它将使用列表推导技术,首先将键设置为变量初始化。使用此变量,循环遍历字典以检查条件使用if语句,即字符串是否在给定的字典中,然后返回结果。
示例
def dict_keys(d, s):
return [key for key in d if key in s]
# The input dictionary and string list
dict1 = {'Tablets': 1, 'Mobiles': 2, 'Earbuds': 3, 'Computer': 4}
stng = ['Mouse', 'Hard Drive', 'Pen Drive', 'Earbuds', 'Tablets']
# Calling function
res = dict_keys(dict1, stng)
print("The result of dictionary keys present in a strings list:\n", res)
输出
The result of dictionary keys present in a strings list:
['Tablets', 'Earbuds']
使用Set()和Intersection()函数
在下面的示例中,递归函数dict_keys()接受两个参数d和s,以查找列表中存在的字典键。然后,它将使用函数返回来设置一些内置函数,例如d.keys(),它会显示字典的视图对象,而intersection(s)会查找两个不同集合之间的共同匹配项。最后,这两个函数都被设置为内置函数list()的参数,它将以列表形式返回结果。
示例
def dict_keys(d, s):
return list(set(d.keys()).intersection(s))
# Create the dictionary and string list
dictionary = {'Television': 1, 'Projector': 2, 'White Board': 3}
strings = ['Projector', 'Box', 'Remote']
# Calling function
res = dict_keys(dictionary, strings)
print("The result of dictionary keys present in a strings list:\n", res)
输出
The result of dictionary keys present in a strings list:
['Projector']
使用简单的循环
在下面的例子中,在名为dict_keys的函数中有两个参数:d_list和s_list。该函数将查找字符串列表中存在的字典键。然后使用空列表来存储结果,并将其存储在变量avl_keys中。接下来,使用for循环,变量k迭代变量d_list,即字典列表。使用if语句判断给定输入字典中的字符串是否存在。然后使用内置的append()方法查找字典键,并将结果返回给变量avl_keys。
示例
def dict_keys(d_list, s_list):
avl_keys = []
for k in d_list:
if k in s_list:
avl_keys.append(k)
return avl_keys
# Create the dictionary and string list
dict1 = {'A': 11, 'B': 12, 'C': 13, 'D': 14, 'E': 15, 'F': 16}
stng = ['M', 'N', 'O', 'E', 'G', 'A', 'C', 'P', 'Q', 'R']
# Calling function
res = dict_keys(dict1, stng)
print("The result of dictionary keys present in a strings list:\n", res)
输出
The result of dictionary keys present in a strings list:
['A', 'C', 'E']
使用filter函数
在下面的示例中,我们将使用递归函数开始程序,该函数接受两个参数-d和s,以接收变量dcn和stng中的字典和字符串的原始输入。接下来,它将使用函数return,该函数使用内置函数lambda计算程序的主要操作,filter()-获取在字典中存在的那些值,并使用list()以列表的形式格式化结果。最后,这样它将生成程序的输出。
示例
def dict_keys(d, s):
return list(filter(lambda k: k in s, d))
# Create the dictionary and string list
dcn = {'abc': 10, 'bcd': 20, 'mno': 30, 'xyz': 40, 'pqr': 50}
stng = ['ab', 'mno', 'bcs', 'xy']
# Calling Function
res = dict_keys(dcn, stng)
print("The result of dictionary keys present in a strings list:\n", res)
输出
The result of dictionary keys present in a strings list:
['mno']
结论
在每个例子中,字典和字符串被用于设置程序的原始输入,其中它被用于操作,即字符串列表中存在的键。在特定需要时,使用了各种内置函数,如filter()、set()、keys()等,以满足特殊需求。