Python – Key with all Characters in String
Last Updated :
27 Apr, 2023
Sometimes, while working with Python Strings, we can have problem in which we need to extract all the keys that have all the characters of given some random key. 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 1: 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().
Python3
test_dict = { 'gfg' : [ 'a' , 'b' , 'c' , 'd' , 'g' ],
'is' : [ 'b' , 'f' , 'e' ],
'best' : [ 'c' , 'd' , 'g' ],
'for' : [ 'n' , 'z' ],
'CS' : [ 'g' , 'd' ] }
print ("The original dictionary is : " + str (test_dict))
test_str = 'gd'
res = list ({key for key, val in test_dict.items()
if all ( chr in val for chr in test_str)})
print ("The keys list : " + str (res))
|
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’]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method 2: Using nested for loops
Step-by-step approach:
- Used nested for loops to extract keys that contain characters of given string
- Append those keys to output list
- Display output list
Python3
test_dict = { 'gfg' : [ 'a' , 'b' , 'c' , 'd' , 'g' ],
'is' : [ 'b' , 'f' , 'e' ],
'best' : [ 'c' , 'd' , 'g' ],
'for' : [ 'n' , 'z' ],
'CS' : [ 'g' , 'd' ] }
print ( "The original dictionary is : " + str (test_dict))
test_str = 'gd'
x = list (test_dict.keys())
y = list (test_dict.values())
res = []
for j in range ( 0 , len (y)):
c = 0
for i in test_str:
if i in y[j]:
c + = 1
if (c = = len (test_str)):
res.append(x[j])
print ( "The keys list : " + str (res))
|
Output
The original dictionary is : {'gfg': ['a', 'b', 'c', 'd', 'g'], 'is': ['b', 'f', 'e'], 'best': ['c', 'd', 'g'], 'for': ['n', 'z'], 'CS': ['g', 'd']}
The keys list : ['gfg', 'best', 'CS']
Time Complexity: O(M*N) M -length of value list N -length of each list in value list
Auxiliary Space: O(N) N- number of keys with characters of string
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...