Say you have a dict called mydict defined below, and you look for a key called 'D'.
mydict = {'A':'a',
'B':'b',
'C':'c'}
mydict['D']
The desired output should be 'D', the exact output you entered. Is there a way to do this with default dict?
As I mentioned in a comment, you can define your own dictionary subclass that does what you want (simply echos missing keys — it doesn't add them):
class MyDefaultDict(dict):
def __missing__(self, key):
return key
mydict = MyDefaultDict({'A':'a',
'B':'b',
'C':'c'})
print(f"{mydict['D']=}") # -> mydict['D']='D'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With