-
Notifications
You must be signed in to change notification settings - Fork 0
Dictionaries
Andrew ZH edited this page Apr 26, 2023
·
5 revisions
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}
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!