Python | Matching a substring key in a dictionary

Method # 1: Using items () + list comprehension
A combination of the above method can be used to accomplish this particular task, in which we simply turn key-value pairs using the items function, and a list comprehension helps with iteration and access logic.

# Python3 code to demonstrate how it works
Matching the substring key in the dictionary
# Using items () + list comprehension

 
# initializing dictionary

test_dict = { `All` : 1 , `have` : 2 , `good` : 3 , `food` : 4 }

 
# initialize the search key string

search_key = `ood`

 
# print original dictionary

print ( "The original dictionary is:" + str (test_dict))

 
# Using items () + list comprehension
Matching the substring key in the dictionary

res = [val for key, val in test_dict.items () if search_key in key]

 
# print result

print ( "Values ​​for substring keys:" + str (res))

Output:

 The original dictionary is: {`All`: 1,` food`: 4, `have`: 2,` good`: 3} Values ​​for substring keys: [4, 3] 

Method # 2: Using dict () + filter () + lambda
A combination of the above functions can be used to accomplish this specific task. In this case, the dict and filter functions are used to convert the result to a dictionary and query a substring in the list, respectively. The lambda performs the task of accessing all key-value pairs.

# Python3 code to demonstrate how it works
Matching a substring key in a dictionary
# Using dict () + filter () + lambda

 
# initializing dictionary

test_dict = { `All` : 1 , `have` : 2 , `good` : 3 , ` food` : 4 }

 
# initialize the search key string

search_key = `ood`

  
# printing the original dictionary

print ( "The original dictionary is:" + str (test_dict))

 
# Using dict () + filter () + lambda
Matching the substring key in the dictionary

res = dict ( filter ( lambda item: search_key in item [ 0 ], test_dict.items ()))

  
# result print

print ( "Key-Value pair for substring keys: " + str (res))

Output:

 The original dictionary is: {`have`: 2,` good`: 3, `food`: 4,` All`: 1} Key-Value pair for substring keys: {`good`: 3,` food`: 4}