w3resource

Python: Check if a specific Key and a value exist in a dictionary

Python dictionary: Exercise-66 with Solution

Write a Python program to check if a specific Key and a value exist in a dictionary.

Sample Solution:

Python Code:

def test(dictt, key, value):
   if any(sub[key] == value for sub in dictt):
       return True
   return False

students = [
        {'student_id': 1, 'name': 'Jean Castro', 'class': 'V'}, 
        {'student_id': 2, 'name': 'Lula Powell', 'class': 'V'},
        {'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'}, 
        {'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'}, 
        {'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'}
        ]


print("\nOriginal dictionary:")
print(students)
print("\nCheck if a specific Key and a value exist in the said dictionary:")
print(test(students,'student_id', 1))
print(test(students,'name', 'Brian Howell'))
print(test(students,'class', 'VII'))
print(test(students,'class', 'I'))
print(test(students,'name', 'Brian Howelll'))
print(test(students,'student_id', 11))

Sample Output:

Original dictionary:
[{'student_id': 1, 'name': 'Jean Castro', 'class': 'V'}, {'student_id': 2, 'name': 'Lula Powell', 'class': 'V'}, {'student_id': 3, 'name': 'Brian Howell', 'class': 'VI'}, {'student_id': 4, 'name': 'Lynne Foster', 'class': 'VI'}, {'student_id': 5, 'name': 'Zachary Simon', 'class': 'VII'}]

Check if a specific Key and a value exist in the said dictionary:
True
True
True
False
False
False

Pictorial Presentation:

Python Dictionary: Check if a specific Key and a value exist in a dictionary.

Flowchart:

Flowchart: Check if a specific Key and a value exist in a dictionary.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to get the total length of all values of a given dictionary with string values.
Next: Write a Python program to invert a given dictionary with non-unique hashable values.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz



Python: Tips of the Day

Free up Memory:

  • Manual garbage collection can be performed on timely or event based mechanism.
import gc
collected_objects = gc.collect()