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

Mitya Sirenef msirenef at lightbird.net
Sat Jan 19 03:18:42 EST 2013


On 01/19/2013 02:35 AM, Mitya Sirenef wrote:
> On 01/19/2013 02:27 AM, Vito De Tullio wrote:
>> Chris Rebert wrote:
>>
>>>> How can I add a key in a thread-safe manner?
>>> I'm not entirely sure, but have you investigated dict.setdefault() ?
>> but how setdefault makes sense in this context? It's used to set a 
>> default
>> value when you try to retrieve an element from the dict, not when you 
>> try to
>> set a new one ...
>>
>
> I guess setdefault with a sentinel default value, then set to your
> new value if d[k] is sentinel?
>
>  - mitya
>
>

Er, that makes no sense.. just setdefault to desired value. -m



-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/




More information about the Python-list mailing list