python dictionary get vs setdefault 1

python dictionary get vs setdefault

# setdefault will insert key with a value of default
# get will not insert key

a = {}
b = a.get('key','value')
print(a,b)
# {} value

a = {}
b = a.setdefault('key','value')
print(a,b)
# {'key': 'value'} value

Here is what the above code is Doing:
1. Create an empty dictionary a
2. Call get on a with the key ‘key’ and the default value ‘value’
3. Print a and b
4. Create an empty dictionary a
5. Call setdefault on a with the key ‘key’ and the default value ‘value’
6. Print a and b

Similar Posts