Python Forum
a dictionary with a key default
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
a dictionary with a key default
#3
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Messages In This Thread
a dictionary with a key default - by Skaperen - Jan-17-2020, 03:01 AM
RE: a dictionary with a key default - by buran - Jan-17-2020, 07:11 AM
RE: a dictionary with a key default - by perfringo - Jan-17-2020, 07:56 AM
RE: a dictionary with a key default - by Skaperen - Jan-18-2020, 12:26 AM
RE: a dictionary with a key default - by Skaperen - Jan-18-2020, 04:14 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020