# -*- coding: utf-8 -*- def deflt(x): print('\nKey', x, 'is not in the dictionary') return 'Default' dicti = {1:'one', 2:'two', 3:'three'} key = 2 print('\ndicti \t\t', dicti) print('\t\t key =',key) print('get \t\t', dicti.get(key, deflt(key))) print('setdefault \t',dicti.setdefault(key, deflt(key))) print('dicti \t\t', dicti) print('pop \t\t', dicti.pop(key, deflt(key))) print('dicti \t\t', dicti) print('setdefault \t',dicti.setdefault(key, deflt(key))) print('dicti \t\t', dicti) ''' Printed outputs: Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] Type "copyright", "credits" or "license" for more information. IPython 7.1.1 -- An enhanced Interactive Python. runfile('C:/Temp/Smazat/Dictionary_Defaults.py', wdir='C:/Temp/Smazat') dicti {1: 'one', 2: 'two', 3: 'three'} key = 2 Key 2 is not in the dictionary # ??? get two Key 2 is not in the dictionary # ??? setdefault two dicti {1: 'one', 2: 'two', 3: 'three'} Key 2 is not in the dictionary # ??? pop two dicti {1: 'one', 3: 'three'} Key 2 is not in the dictionary setdefault Default dicti {1: 'one', 3: 'three', 2: 'Default'} ''' ''' Dictionary Help : .get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError .pop(key[, default]) If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised. .setdefault(key[, default]) If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None. '''