value = my_dict.setdefault(key, default) returns the value for an existing key. If the key is missing, it inserts the key with the supplied default value and returns that value.
See the complete Dictionary Methods table for the other dictionary operations in this cluster.
my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.setdefault('b')
print(x)
print(my_dict)
Output is here
Two
{'a': 'One', 'b': 'Two', 'c': 'Three'}
my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.setdefault('d')
print(x)
print(my_dict)
Output (key d with value as None is added )
None
{'a': 'One', 'b': 'Two', 'c': 'Three', 'd': None}
my_dict={'a':'One','b':'Two','c':'Three'}
x=my_dict.setdefault('d','Four')
print(x)
print(my_dict)
Output
Four
{'a': 'One', 'b': 'Two', 'c': 'Three', 'd': 'Four'}
my_dict = {'a': 1, 'b': 2}
x = my_dict.setdefault('c', [3, 4])
print(x) # Output: [3, 4]
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': [3, 4]}
nested_dict = {'person': {'name': 'Alice'}}
nested_dict.setdefault('person', {}).setdefault('age', 25)
print(nested_dict) # Output: {'person': {'name': 'Alice', 'age': 25}}
my_list = ['apple', 'banana', 'apple', 'orange']
count_dict = {}
for item in my_list:
count_dict.setdefault(item, 0)
count_dict[item] += 1
print(count_dict) # Output: {'apple': 2, 'banana': 1, 'orange': 1}
data = {'name': 'Alice'}
age = data.setdefault('age', 30)
print(age) # Output: 30
print(data) # Output: {'name': 'Alice', 'age': 30}
my_dict = {}
my_dict.setdefault('fruits', []).append('apple')
my_dict.setdefault('fruits', []).append('banana')
print(my_dict) # Output: {'fruits': ['apple', 'banana']}
words = ['cat', 'dog', 'elephant', 'bird']
length_dict = {}
for word in words:
length_dict.setdefault(len(word), []).append(word)
print(length_dict) # Output: {3: ['cat', 'dog'], 8: ['elephant'], 4: ['bird']}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.