+1 vote
in Programming Languages by (8.9k points)
I want to add keys/values to an existing Python dictionary. However, the value should not be updated if the key is already present. To do this, I need to check whether the key exists. Is there any way to avoid checking if a key exists before updating its value?

1 Answer

+2 votes
by (71.8k points)
selected by
 
Best answer

You can use the setdefault() function to avoid checking if a key exists before updating its value. This function will add the new key/value to the dictionary. If the key already exists, this function will not update its value.

Here is an example:

>>> aa = {'a': 1, 'b': 2, 'c': 3}

>>> aa

{'a': 1, 'b': 2, 'c': 3}

>>> aa.setdefault('d', 4)

4

>>> aa

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

>>> aa.setdefault('a', 4)

1

>>> aa

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

When I tried to add the new key 'd', the dictionary was updated. But when I tried to add 'a', the value of 'a' remained the same.

...