setdefault() retrieves the value of a specified key in a dictionary

setdefault(), takes two arguments , one is key and other one is value ( optional ) .

Returns : the value of the input key ( if available ) .

The original dictionary is changed after this method if the key is added.

Getting the value of the input key

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'}

If input key is not available then key is added.

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}

Adding new key with value

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'}

Example 1: Setting Default Value with a Different Data Type

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]}

Example 2: Using setdefault() with Nested Dictionaries

nested_dict = {'person': {'name': 'Alice'}}
nested_dict.setdefault('person', {}).setdefault('age', 25)
print(nested_dict)  # Output: {'person': {'name': 'Alice', 'age': 25}}

Example 3: Counting Occurrences in a List with setdefault()

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}

Example 4: Handling Missing Keys with Default Values

data = {'name': 'Alice'}
age = data.setdefault('age', 30)
print(age)  # Output: 30
print(data)  # Output: {'name': 'Alice', 'age': 30}

Example 5: Appending to a List in a Dictionary Using setdefault()

my_dict = {}
my_dict.setdefault('fruits', []).append('apple')
my_dict.setdefault('fruits', []).append('banana')
print(my_dict)  # Output: {'fruits': ['apple', 'banana']}

Example 6: Grouping Strings by Length Using setdefault()

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']}

All dictionary methods
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer