Python program to remove keys with substring values.

In this python dictionary program, we will remove keys with substring values from a dictionary.

Steps to solve the program
  1. Take a dictionary and a list of substrings as input and create an empty dictionary.
  2. Use for loop to iterate over keys and values of the dictionary.
  3. 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.
  4. Add only those kay-value pairs in which the substring does not exist to the empty dictionary.
  5. 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'}
				
			

remove keys with values greater than n.

access the dictionary key.

Leave a Comment