📜  用字典中的子串提取键值对的Python程序

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

用字典中的子串提取键值对的Python程序

给定一个字典列表,提取在特定键中存在子字符串的所有字典。

方法#1:使用列表理解

这是可以执行此任务的方法之一。在此,我们迭代所有字典并使用 in运算符检查键的值子字符串是否存在。

Python3
# Python3 code to demonstrate working of
# Dictionaries with Substring values
# Using list comprehension
  
# initializing lists
test_list = [{"Gfg": "4", "best": "1"},
             {"Gfg": "good for CS", "best": "8"},
             {"Gfg": "good CS content", "best": "10"}]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K key
K = "Gfg"
  
# initializing target value
sub_str = "CS"
  
# list comprehension to extract values with
# substring values using in operator
res = [val for val in test_list if sub_str in val[K]]
  
# printing result
print("Dictionaries with particular substring values : " + str(res))


Python3
# Python3 code to demonstrate working of
# Dictionaries with Substring values
# Using map() + in operator
  
# initializing lists
test_list = [{"Gfg": "4", "best": "1"},
             {"Gfg": "good for CS", "best": "8"},
             {"Gfg": "good CS content", "best": "10"}]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K key
K = "Gfg"
  
# initializing target value
val = "CS"
  
# map() used to perform filtering
res = list(map(lambda sub: val in sub[K], test_list))
res = [test_list[idx] for idx, ele in enumerate(res) if res[idx]]
  
# printing result
print("Dictionaries with particular substring values : " + str(res))


输出:

方法#2:使用 map() + in运算符

这是可以执行此任务的另一种方式。在此,我们使用 map() + lambda函数提取具有所需子字符串的所有值。 in运算符用于检查键值中的子字符串。

蟒蛇3

# Python3 code to demonstrate working of
# Dictionaries with Substring values
# Using map() + in operator
  
# initializing lists
test_list = [{"Gfg": "4", "best": "1"},
             {"Gfg": "good for CS", "best": "8"},
             {"Gfg": "good CS content", "best": "10"}]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K key
K = "Gfg"
  
# initializing target value
val = "CS"
  
# map() used to perform filtering
res = list(map(lambda sub: val in sub[K], test_list))
res = [test_list[idx] for idx, ele in enumerate(res) if res[idx]]
  
# printing result
print("Dictionaries with particular substring values : " + str(res))

输出: