Dictionaries - AndrewMZ6/python_cheat_sheet GitHub Wiki
Dict creation:
Single key-value pair
>>> d = dict( (('one', 1), ) ) # using tuple
>>> d = dict( [('one', 1), ] ) # using list
>>> d = dict( one=1 ) # using keyword argument
{'one': 1}
__missing__
method
When accesing non-existing key in a dictionary magic method __missing__
is called with requested key as argument. We can check it like this
>>> class MyDict(dict):
def __missing__(self, key):
print(f"You requested key \"{key}\", but it's missing!")
>>> md = MyDict( one=1 )
>>> md
{'one': 1}
>>> md['NoneExistingKey']
You requested key "NoneExistingKey", but it's missing!