w3resource

PCEP Certification Practice: Checking the Existence of Dictionary Keys

PCEP Certification Practice Test - Questions, Answers and Explanations

Below is a set of questions for the Certified Entry-Level Python Programmer (PCEP) examination focusing on the subtopic "dictionaries: checking the existence of keys." The questions use various formats, including single- and multiple-select questions, fill-in-the-gap, code fill, code insertion, sorting, and more.

Question 1: What is the most common way to check if a key exists in a dictionary?

  1. my_dict.has_key('key')
  2. 'key' in my_dict
  3. my_dict['key']
  4. my_dict.key_exists('key')

Answer: B) 'key' in my_dict

Explanation: The expression 'key' in my_dict is the most common and Pythonic way to check if a key exists in a dictionary.

Question 2: Which of the following methods can be used to check if a key exists in a dictionary? (Choose all that apply)

  1. if 'key' in my_dict:
  2. if my_dict.get('key') is not None:
  3. if my_dict.has_key('key'):
  4. if 'key' not in my_dict:

Answer: A) if 'key' in my_dict:
B) if my_dict.get('key') is not None:
D) if 'key' not in my_dict:

Explanation: You can check if a key exists using 'key' in my_dict or by using get() with a check for None. The not in syntax checks if the key does not exist. The has_key() method is deprecated and not used in Python 3.x.

Question 3: Complete the code to print "Key exists" if the key 'age' exists in the dictionary person.

person = {'name': 'Alice', 'age': 30}
if ______:
    print("Key exists")

Answer: 'age' in person

Explanation: The expression 'age' in person checks if the key 'age' exists in the dictionary.

Question 4: What will be the output of the following code?

my_dict = {'a': 1, 'b': 2, 'c': 3}
if 'b' in my_dict:
    print("Found")
else:
    print("Not Found")
  1. Found
  2. Not Found
  3. Error
  4. None

Answer: A) Found

Explanation: The key 'b' exists in my_dict, so the code prints "Found".

Question 5: Insert the correct code to print "Key not found" if the key 'city' is not present in the dictionary person.

person = {'name': 'Alice', 'age': 30}
if ______:
    print("Key not found")

Answer: 'city' not in person

Explanation: The expression 'city' not in person checks if the key 'city' does not exist in the dictionary.

Question 6: What is the result of the following code?

person = {'name': 'Bob', 'age': 25}
if 'address' in person:
    print("Address found")
else:
    print("Address not found")
  1. Address found
  2. Address not found
  3. Error
  4. None

Answer: B) Address not found

Explanation: The key 'address' does not exist in the dictionary person, so the code prints "Address not found".

Question 7: Which of the following statements correctly check for the existence of a key in a dictionary? (Choose all that apply)

  1. if 'key' in my_dict:
  2. if my_dict.get('key') is None:
  3. if my_dict.get('key', 'default') == 'default':
  4. if my_dict['key'] == None:

Answer: A) if 'key' in my_dict:
B) if my_dict.get('key') is None:

Explanation: Option A checks for the existence of the key directly. Option B Checks if the key exists and its value is None or the key doesn't exist

Question 8: Arrange the steps to correctly check if a key exists in a dictionary and print a message accordingly.

  1. Use an if statement to check if the key exists.
  2. Print "Key exists" if the key is found.
  3. Define the dictionary person.

Answer: 3, 1, 2

Explanation: First, define the dictionary, then check if the key exists using an if statement, and finally print the message if the key is found.

Question 9: Complete the code to print "Key found" if the key 'email' exists in the dictionary contact.

contact = {'name': 'John', 'phone': '123-456-7890'}
if ______:
    print("Key found")

Answer: 'email' in contact

Explanation: The expression 'email' in contact checks if the key 'email' exists in the dictionary.

Question 10: What will be the output of the following code?

inventory = {'apples': 10, 'bananas': 5}
if 'oranges' not in inventory:
    print("Out of stock")
  1. Out of stock
  2. In stock
  3. Error
  4. None

Answer: A) Out of stock

Explanation: The key 'oranges' does not exist in the inventory dictionary, so the code prints "Out of stock".

Question 11: Insert the correct code to check if the key 'username' does not exist in the dictionary user_data and add it if it doesn't.

user_data = {'email': '[email protected]'}
if ______:
    user_data['username'] = 'new_user'

Answer: 'username' not in user_data

Explanation: The expression 'username' not in user_data checks if the key 'username' is missing from the dictionary, and if it is, a new key-value pair is added.

Question 12: What will happen if you try to check the existence of a key using the expression if my_dict['key'] when the key does not exist?

  1. A new key-value pair is added to the dictionary.
  2. The program raises a KeyError.
  3. The program returns None.
  4. The program prints False.

Answer: B) The program raises a KeyError.

Explanation: Trying to access a non-existent key using square brackets will raise a KeyError.

Question 13: Which of the following are safe ways to check if a key exists in a dictionary without raising an error? (Choose all that apply)

  1. 'key' in my_dict
  2. my_dict.get('key')
  3. my_dict['key']
  4. 'key' not in my_dict

Answer: A) 'key' in my_dict
B) my_dict.get('key')
D) 'key' not in my_dict

Explanation: The in and not in operators are safe for checking the existence of a key. The get() method also safely returns None if the key does not exist, but using square brackets (my_dict['key']) will raise an error if the key is not found.

Question 14: Arrange the steps to correctly check if a key exists and return a default value if it does not.

  1. Use the get() method with a default value.
  2. Define the dictionary config.
  3. Print the retrieved value or the default value

Answer: 2, 1, 3

Explanation: First, define the dictionary, then use the get() method with a default value to check for the key, and finally print the result.

Question 15: Complete the code to safely retrieve the value of the key 'password' from the dictionary login_info or return 'Not set' if the key does not exist.

login_info = {'username': 'admin'}
password = login_info.get('password', ______)
print(password)

Answer: 'Not set'

Explanation: The get() method is used with a default value of 'Not set', which is returned if the key 'password' does not exist in the dictionary.

Question 16: What will be the output of the following code?

settings = {'theme': 'dark', 'notifications': True}
if 'volume' not in settings:
    print("Default volume setting")
  1. None
  2. Default volume setting
  3. Error
  4. True

Answer: B) Default volume setting

Explanation: The key 'volume' is not present in the settings dictionary, so the code prints "Default volume setting".

17. Insert the correct method to retrieve the value of the key 'api_key' from the dictionary config, or return 'No API key' if the key does not exist.

config = {'version': '1.0'}
api_key = config.______ ('api_key', 'No API key')
print(api_key)

Answer: get

Explanation: The get() method is used with a default value of 'No API key', which is returned if the key 'api_key' is not found.

Question 18: Which statement is true about checking the existence of keys in a Python dictionary?

  1. Using my_dict['key'] will return None if the key doesn't exist.
  2. Using 'key' in my_dict will raise a KeyError if the key doesn't exist.
  3. Using my_dict.get('key') is a safe way to check for the existence of a key.
  4. Using my_dict.keys() is required to check if a key exists.

Answer: C) Using my_dict.get('key') is a safe way to check for the existence of a key.

Explanation: The get() method is a safe way to check for the existence of a key because it returns None (or a specified default value) if the key does not exist.

Question 19: Which of the following methods allow you to check for the existence of a key and retrieve its value if it exists? (Choose all that apply)

  1. my_dict['key']
  2. my_dict.get('key')
  3. 'key' in my_dict
  4. my_dict.setdefault('key', 'default')

Answer: B) my_dict.get('key')
D) my_dict.setdefault('key', 'default')

Explanation: The get() method retrieves the value if the key exists or returns None. The setdefault() method retrieves the value if the key exists or sets it to a default value if it doesn't. Option A will raise a KeyError if the key doesn't exist, and Option C only checks for existence without retrieving the value.

Question 20: Arrange the steps to correctly check if a key exists in a dictionary and add a new key-value pair if it doesn't.

  1. Use the not in operator to check if the key exists.
  2. Add the new key-value pair.
  3. Define the dictionary preferences.

Answer: 3, 1, 2

Explanation: First, define the dictionary, then use the not in operator to check for the key, and finally add the new key-value pair if it doesn’t exist.

Question 21: Complete the code to add the key 'location' with the value 'unknown' to the dictionary data only if the key doesn't already exist.

data = {'name': 'Alice'}
if 'location' ______ data:
    data['location'] = 'unknown'

Answer: not in

Explanation: The expression 'location' not in data checks if the key 'location' does not exist in the dictionary, and if it doesn't, the key is added with the value 'unknown'.

Question 22: What will be the output of the following code?

preferences = {'theme': 'light', 'language': 'English'}
if 'font_size' not in preferences:
    preferences['font_size'] = '12pt'
print(preferences)
  1. {'theme': 'light', 'language': 'English'}
  2. {'theme': 'light', 'language': 'English', 'font_size': '12pt'}
  3. {'font_size': '12pt'}
  4. Error

Answer: B) {'theme': 'light', 'language': 'English', 'font_size': '12pt'}

Explanation: The key 'font_size' is not in the dictionary, so it is added with the value '12pt'.

Question 23: Insert the correct code to check if the key 'admin' exists in the dictionary users and print a message if it does.

users = {'user1': 'Alice', 'user2': 'Bob', 'admin': 'Charlie'}
if ______:
    print("Admin exists")

Answer: 'admin' in users

Explanation: The expression 'admin' in users checks if the key 'admin' exists in the dictionary, and if it does, the message "Admin exists" is printed.

Question 24: What will happen if you use the get() method to check for a key that does not exist and provide a default value?

  1. The method returns the default value.
  2. The method raises a KeyError.
  3. The method returns None.
  4. The method adds the key to the dictionary with the default value.

Answer: A) The method returns the default value

Explanation: The get() method returns the provided default value if the key does not exist in the dictionary.

Question 25: Which of the following statements correctly check for the existence of a key in a dictionary and handle it safely? (Choose all that apply)

  1. if 'key' in my_dict:
  2. value = my_dict.get('key', 'default_value')
  3. if 'key' not in my_dict:
  4. value = my_dict['key']

Answer: A) if 'key' in my_dict:
B) value = my_dict.get('key', 'default_value')

Explanation: Options A, and B correctly check for the existence of a key and handle the situation safely. Option C and D would raise a KeyError if the key does not exist.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python/certificate/data-collections-dictionaries-checking-the-existence-of-keys.php