Python – Key with all Characters in String

Sometimes, while working with Python Strings, we can have problem in which we need to extract all the keys that have all the characters in the character value list. This kind of problem has application has many domains such as day-day programming. Let’s discuss a way in which this problem can be solved.

Method : Using all() + dictionary comprehension
The combination of above functionalities can be used to solve this problem. In this, we use all() to perform check in whole of dictionary and extraction of items using items().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Key with all Characters in String
# Using all() + dictionary comprehension
  
# initializing dictionary
test_dict = { 'gfg' : ['a', 'b', 'c', 'd', 'g'],
              'is' : ['b', 'f', 'e'],
              'best' : ['c', 'd', 'g'],
              'for' : ['n', 'z'],
              'CS' : ['g', 'd'] }
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing keys 
test_str = 'gd'
  
# Key with all Characters in String
# Using all() + dictionary comprehension
res = list({key for key, val in test_dict.items() 
            if all(chr in val for chr in test_str)})
  
# printing result 
print("The keys list : " + str(res)) 

chevron_right


Output :

The original dictionary is : {‘is’: [‘b’, ‘f’, ‘e’], ‘best’: [‘c’, ‘d’, ‘g’], ‘for’: [‘n’, ‘z’], ‘CS’: [‘g’, ‘d’], ‘gfg’: [‘a’, ‘b’, ‘c’, ‘d’, ‘g’]}
The keys list : [‘best’, ‘CS’, ‘gfg’]

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.