To add an element to a Python dictionary if a key does not exist, you can use the “dict.setdefault()” method, “dict.get()” method, or a “conditional expression” with the “in” keyword.
Method 1: Using the dict.setdefault()
The setdefault() method returns the value of a key if it exists. Otherwise, it adds the key with a specified value and returns that value.
Example
main_dict = {'a': 1, 'b': 2}
key = 'c'
value = 3
main_dict.setdefault(key, value)
print(main_dict)
Output
{'a': 1, 'b': 2, 'c': 3}
Method 2: Using the dict.get()
The get() method returns the value of a key if it exists; otherwise, it returns a specified default value (or None if no default value is provided).
Example
main_dict = {'a': 1, 'b': 2}
key = 'c'
value = 3
if main_dict.get(key) is None:
main_dict[key] = value
print(main_dict)
Output
{'a': 1, 'b': 2, 'c': 3}
Method 3: Using conditional expression with “in” keyword
You can use the “in” keyword to check if a key exists in a dictionary. If the key does not exist, add the key-value pair to the dictionary.
main_dict = {'a': 1, 'b': 2}
key = 'c'
value = 3
if key not in main_dict:
main_dict[key] = value
print(main_dict)
Output
{'a': 1, 'b': 2, 'c': 3}
All three methods add an element to the dictionary if the key does not already exist, but the dict.setdefault() method is the most concise.
That’s it.