thread safe python dictionaries?
Question: I have a function call that starts 10 threads. Before the start of these
threads , I have

    
    
    from collections import defaultdict
    output = defaultdict(dict)
    

and output is empty.

Each thread will generate data to write to the dictionary.

Something like:

    
    
    output['water'] = 'h20'
    output['fire'] = 'delta of oxygen'
    ....
    

The threads will only add items and they do not iterate over any of the other
items or modify any other items. `output['water']` being an item that is
different from `output['fire']`. I can also guarantee that no two threads are
going to create the same item. That is, each thread T has a unique i. In code:
output[i] is unique per thread.

Is this dictionary thread safe in this regard?


Answer: Yes.

If you are using CPython and strings as keys, then yes. The GIL in CPython
ensures only one thread executes bytecode at a time, and setting a key to a
value in a dict happens in a single opcode, `STORE_SUBSCR`. If you are not
using CPython, or you are using a key that has custom `__hash__`, `__eq__`, or
`__cmp__` methods, all bets are off. If I had a soapbox, I'd hop on it and
warn you of the evils of relying on implementation details like this for
correctness. It's more pythonic of you to write something that works only for
the case and in the environment where it will be used, since doing otherwise
could be seen as a premature optimization. Enjoy your working code!

    
    
    >>> from dis import dis
    >>> dis(compile('output = defaultdict(dict); output["water"] = "H2O"', 'example', 'exec'))
      1           0 LOAD_NAME                0 (defaultdict)
                  3 LOAD_NAME                1 (dict)
                  6 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
                  9 STORE_NAME               2 (output)
                 12 LOAD_CONST               0 ('H2O')
                 15 LOAD_NAME                2 (output)
                 18 LOAD_CONST               1 ('water')
                 21 STORE_SUBSCR
                 22 LOAD_CONST               2 (None)
                 25 RETURN_VALUE
    

This has been [discussed
elsewhere](http://bytes.com/topic/python/answers/655729-thread-safety-dict).

