In this python dictionary program, we will remove keys with substring values from a dictionary.
Steps to solve the program
- Take a dictionary and a list of substrings as input and create an empty dictionary.
- Use for loop to iterate over keys and values of the dictionary.
- Using an if statement and a for loop inside the any() function check whether the substring from the list exists in the list values or not.
- Add only those kay-value pairs in which the substring does not exist to the empty dictionary.
- Print the output.
D1 = {1:'sqatools is best',2:'for learning python'}
substr = ['best','excellent']
res = dict()
for key, val in D1.items():
if not any(ele in val for ele in substr):
res[key] = val
print(res)
Output :
{2: 'for learning python'}