# Python – Check if particular value is present corresponding to K key

PythonServer Side ProgrammingProgramming

When it is required to check if particular value is present corresponding to a key ‘K’, a list comprehension is used.

Below is a demonstration of the same −

## Example

Live Demo

my_list = [{"python" : "14", "is" : "great", "fun" : "1"},{"python" : "cool", "is" : "fun", "best" : "81"},{"python" : "93", "is" : "CS", "amazing" : "16"}]

print("The list is :")
print(my_list)

K = "python"
print("The value of K is ")
print(K)

value = "cool"

my_result = value in [index[K] for index in my_list]

print("The result is :")

if(my_result == True):
print("The value is present in with respect to key ")
else:
print("The value isn't present with respect to key")

## Output

The list is :
[{'python': '14', 'is': 'great', 'fun': '1'}, {'python': 'cool', 'is': 'fun', 'best': '81'}, {'python': '93', 'is': 'CS', 'amazing': '16'}]
The value of K is
python
The result is :
The value is present in with respect to key

## Explanation

• A list of dictionary elements is defined and is displayed on the console.

• A value for K is defined and displayed on console.

• Another string is defined.

• The list is iterated over using list comprehension and the index of the K value is searched for in the list of dictionary.

• This is assigned to a variable.

• Based on if this variable is ‘True’ or ‘False’, relevant message is displayed on the console.

Updated on 06-Sep-2021 07:50:18