w3resource

Python: Check multiple keys exists in a dictionary


33. Check if Multiple Keys Exist in a Dictionary

Write a Python program to check if multiple keys exist in a dictionary.

Visual Presentation:

Python Dictionary: Check multiple keys exists in a dictionary.
Python Dictionary: Check multiple keys exists in a dictionary.

Sample Solution:

Python Code:

# Create a dictionary 'student' with key-value pairs representing a student's information.
student = {
  'name': 'Alex',
  'class': 'V',
  'roll_id': '2'
}

# Check if the set of keys in 'student' contains the keys 'class' and 'name'.
print(student.keys() >= {'class', 'name'})

# Check if the set of keys in 'student' contains the keys 'name' and 'Alex'.
# Note that 'Alex' is not a key, so this check will always be False.
print(student.keys() >= {'name', 'Alex'})

# Check if the set of keys in 'student' contains the keys 'roll_id' and 'name'.
print(student.keys() >= {'roll_id', 'name'}) 

Sample Output:

True                                                                                                          
False                                                                                                         
True

For more Practice: Solve these Related Problems:

  • Write a Python program to verify if a list of keys are all present in a dictionary.
  • Write a Python program to use all() with a list comprehension to check for multiple keys in a dictionary.
  • Write a Python program to implement a function that returns True if every key in a given list exists in the dictionary.
  • Write a Python program to compare the keys of a dictionary with a given set and output whether all specified keys are found.

Python Code Editor:

Previous: Write a Python program to print a dictionary line by line.
Next: Write a Python program to count number of items in a dictionary value that is a list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.