dict instances have a .get()
method that is similar to the .pop()
they also have, except nothing is removed and the key is not in the dict instance, it returns None.
why do we need to have this? is it so we can have shorter/smaller code, since this can be done without it?
if so, then why not have a .put()
method that has an optional 3nd argument for an alternate value to put in under the key in the 1st argument if the key will be new (does not already exist) in that dict instance?
(May-07-2023, 02:53 AM)buran Wrote: [ -> ]dict.setdefault
is that new in 3.11? it is not there in my 3.8.
then i had to have mis-typed the name. i see it in dir({})
. but this method is not doing what i expect it to do. the doc is vague and my expectation is had before i read this doc so that may be why it is vague to me and why i still expect a different behavior. i don't understand why it needs a key.
(May-12-2023, 12:04 AM)Skaperen Wrote: [ -> ]this method is not doing what i expect it to do. the doc is vague and my expectation is had before i read this doc so that may be why it is vague to me and why i still expect a different behavior.
setdefault()
is just like
get()
but it inserts the default value in the dict if the key is missing.
(May-12-2023, 12:04 AM)Skaperen Wrote: [ -> ]i don't understand why it needs a key.
Without supplying a key, how would you know where (what key) to assign the [default] value?
spam = {} # empty dict
foo = spam.setdefault('eggs', 'foo') # of course you don't HAVE TO assign the return value to a name
print(spam)
print(foo)
bar = spam.setdefault('eggs', 'bar')
print(spam)
print(bar)
Output:
{'eggs': 'foo'}
foo
{'eggs': 'foo'}
foo
(May-06-2023, 11:55 PM)Skaperen Wrote: [ -> ]why not have a .put() method that has an optional 3nd argument for an alternate value to put in under the key in the 1st argument if the key will be new (does not already exist) in that dict instance?
It's doing exactly that, except that I don't understand what would be the purpose of the second argument of your
dict.put()
- i.e. it doesn't make sense to have 3 arguments for what you describe
(May-12-2023, 08:05 AM)buran Wrote: [ -> ]I don't understand what would be the purpose of the second argument of your dict.put() - i.e. it doesn't make sense to have 3 arguments for what you describe
As far as I understand the description, it is
def put(dic, k, v, w=None):
dic[k] = (v if k in dic else w)
Use cases are hard to find.
(May-12-2023, 08:36 AM)Gribouillis Wrote: [ -> ]As far as I understand the description, it is
Basically one value if key already in dict and another value if key not yet in dict?
(May-12-2023, 08:36 AM)Gribouillis Wrote: [ -> ]Use cases are hard to find.
Agree