Here are three ways to add an element if a key does not exist in Python dictionary:
- Using setdefault()
- Using if statement
- Using get()
Method 1: Using setdefault()
The dict.setdefault() method checks if a key exists in the dictionary, and if not, it adds the key with a specified default value.
If the key does exist, it leaves the dictionary unchanged.
Visual Representation
Example
# dictionary
icc_dict = {'IND': 1, 'AUS': 2}
# Add a new element if the key does not exist
icc_dict.setdefault('NZ', 4)
print(icc_dict)
# If the key already exists, the dictionary remains unchanged
icc_dict.setdefault('AUS', 5)
print(icc_dict)
Output
{'IND': 1, 'AUS': 2, 'NZ': 4}
{'IND': 1, 'AUS': 2, 'NZ': 4}
If no default value is passed, None is added as the default value.
Visual Representation
Example
icc_dict.setdefault('SA')
print(icc_dict)
Output
{'IND': 1, 'AUS': 2, 'NZ': 4, 'SA': None}
Method 2: Using if statement
The if statement checks whether a key exists in the dictionary and, if not, adds the key-value pair to the dictionary.
Visual Representation
Example
# dictionary
icc_dict = {'IND': 1, 'AUS': 2}
if 'NZ' not in icc_dict:
icc_dict['NZ'] = 4
print(icc_dict)
Output
{'IND': 1, 'AUS': 2, 'NZ': 4}
Method 3: Using get()
You can use dict.get() in combination with an assignment to add a key-value pair if the key does not exist.
This method is less efficient than the two previously mentioned methods, but still a valid approach and can be useful in certain contexts.
Example
# dictionary
icc_dict = {'IND': 1, 'AUS': 2}
# Use dict.get() to check the key and add it if it doesn't exist
if icc_dict.get('NZ') is None:
icc_dict['NZ'] = 4
print(icc_dict)
Output
{'IND': 1, 'AUS': 2, 'NZ': 4}
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.