Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defaultdict return key as default [duplicate]

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?

like image 955
Jacob Bayer Avatar asked Jun 04 '26 19:06

Jacob Bayer


1 Answers

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'

like image 137
martineau Avatar answered Jun 06 '26 08:06

martineau



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!