- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Check if particular value is present corresponding to K key
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
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.
Advertisements