+1 vote
in Programming Languages by (14.2k points)

Using the setdefault() method, I do not have to worry about checking if a particular key is present in the dictionary. However, I am unsure how to use it. Can you give me an example explaining how to use this dictionary method?

1 Answer

+3 votes
by (86.3k points)
selected by
 
Best answer

The setdefault() method in Python allows you to get the value of a key if it exists in the dictionary, and if not, it inserts the key with a default value and returns that value. It is very useful when you don't want to manually check if a key exists before adding or updating it.

In the following example, I declared a dictionary 'aa'. Using the setdefault() method, I am either adding a value to an existing key or adding a new key with some value.

>> aa={}

>>> aa.setdefault('a',set()).add(2)

>>> aa

{'a': {2}}

>>> aa.setdefault('a',set()).add(3)

>>> aa

{'a': {2, 3}}

>>> aa.setdefault('b',set()).add(13)

>>> aa

{'a': {2, 3}, 'b': {13}}


...