Settings

Theme

Is there any good reason why no set method in Python dict?

2 points by somesun a year ago · 3 comments · 1 min read

Reader

many times , when I write code when using dict d = {} d['name'] = 'John' d['age'] = 40

something like that , i wonder why there is not set method on dict, because get method is in there, and there even a setdefault method , which is very confusing , since it's main usage is to get value

anyway , i dont' see a good reason not to put a set method like this

def set (self, k, v, exists=True): ''' if exists is False , will not overwrite current key if it's alreay there ''' ...

actually , since no set method before, if add this in new python version , there is no compatible issue

zahlman a year ago

> ''' if exists is False , will not overwrite current key if it's alreay there '''

...That's what `setdefault` does. It just also returns the value, which you're free to ignore. (The other version is what ordinary key assignment does.)

Also, that's really not a clear name for the parameter at all.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection