Python Forum
a dictionary with a key default - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: a dictionary with a key default (/thread-23788.html)



a dictionary with a key default - Skaperen - Jan-17-2020

i can use the method .get() on a dictionary to use a single specific default. i would like to have a simple means like that which can be inserted into an expression which will return the value of the key itself if there is no matching key in the dictionary. i do not want something that requires expressing the key twice, so i can use costly key expressions and/or key expressions with side effects.


RE: a dictionary with a key default - buran - Jan-17-2020

express the key on separate line and assign to name, then use that name twice in get() call or define custom class that inherit from dict but override get() method and use it instead of built in class


RE: a dictionary with a key default - perfringo - Jan-17-2020

More often that not I have trouble grasping the question. There is side effect of adding new key value pair but anyways:

>>> key = 'oh my'                                                   
>>> d = {'meaning of life': 42}                                     
>>> d.setdefault(key, key)                                          
'oh my'
>>> d.setdefault('meaning of life', 'no way')                       
42
>>> d                                                               
{'meaning of life': 42, 'oh my': 'oh my'}
With another side effect:

>>> key = 'oh no'                                                   
>>> d = {'meaning of life': 42}                                     
>>> d.pop(d.setdefault(key, key))                                   
'oh no'
>>> d                                                               
{'meaning of life': 42}
>>> d.pop(d.setdefault('meaning of life', 'oh no'))                 
--------------------------------------------------------------------------
/.../
----> 1 d.pop(d.setdefault('meaning of life', 'oh no'))
KeyError: 42



RE: a dictionary with a key default - Skaperen - Jan-18-2020

i was wanting to put this as an expression inside a comprehension.


RE: a dictionary with a key default - Skaperen - Jan-18-2020

the dictionary is mapping some aliases for some strings used in some comprehensions.