Safely add a key to a dict only if it does not already exist?

Chris Angelico rosuav at gmail.com
Sat Jan 19 09:23:51 CET 2013


On Sat, Jan 19, 2013 at 7:16 PM, Vito De Tullio <vito.detullio at gmail.com> wrote:
> yeah, sure, but with a fixed value :)
>
> I mean: if the value is not important, why bother at all trying not to
> override it with an if or a lock or other tecniques? doing
>
>     d['key'] = 'fixed_value'
>
> multiple times in different threads is not a problem in my eyes...

How fixed is fixed?

>>> d={}
>>> d.setdefault("foo",1)
1
>>> d.setdefault("bar",2)
2
>>> d
{'bar': 2, 'foo': 1}

If list append is guaranteed atomic, and since setdefault is
apparently atomic, then this would be a thread-safe way to maintain a
dictionary of lists:

>>> d={}
>>> lst=d.setdefault("foo",[])
>>> lst.append(1)

Are those guarantees made?

ChrisA



More information about the Python-list mailing list