Python – Check if particular value is present corresponding to K key
Last Updated :
08 Mar, 2023
Given a list of dictionaries, check whether particular key-value pair exists or not.
Input : [{“Gfg” : “4”, “is” : “good”, “best” : “1”}, {“Gfg” : “9”, “is” : “CS”, “best” : “10”}], K = “Gfg”, val = “find”
Output : False
Explanation : No value of “Gfg” is “find”.
Input : [{“Gfg” : “4”, “is” : “good”, “best” : “1”}, {“Gfg” : “9”, “is” : “CS”, “best” : “10”}], K = “Gfg”, val = 4
Output : True
Explanation : 4 present as “Gfg” value.
Method #1 : Using list comprehension
This is one of the ways in which this task can be performed. In this, we extract dictionaries using list comprehension and then use “in” operator to check if it has any values in it.
Python3
test_list = [{ "Gfg" : "4" , "is" : "good" , "best" : "1" },
{ "Gfg" : "find" , "is" : "better" , "best" : "8" },
{ "Gfg" : "9" , "is" : "CS" , "best" : "10" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
val = "find"
res = val in [sub[K] for sub in test_list]
print ( "Is key-val pair present? : " + str (res))
|
Output
The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': 'find', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
Is key-val pair present? : True
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using map() + in operator
This is yet another way in which this task can be performed. In this task of getting values corresponding to a particular key is performed using map(), extending function to each dictionary.
Python3
test_list = [{ "Gfg" : "4" , "is" : "good" , "best" : "1" },
{ "Gfg" : "find" , "is" : "better" , "best" : "8" },
{ "Gfg" : "9" , "is" : "CS" , "best" : "10" }]
print ( "The original list : " + str (test_list))
K = "Gfg"
val = "find"
res = val in list ( map ( lambda sub : sub[K], test_list))
print ( "Is key-val pair present? : " + str (res))
|
Output
The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': 'find', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
Is key-val pair present? : True
Time Complexity: O(n) where n is the number of elements in the list “test_list”. This is because we’re using the built-in map() + in operator both has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), no extra space is required
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...