Apr-25-2018, 07:11 PM
I'm not observing the same thing as you
Output:>>> d = {0:{'lfm':1, 'lfg':1, 'lwg': 1, 'lwm': 1},1:{'lfm': 1, 'lfg': 1, 'lwg': 1, 'lwm': 1}}
>>> def populate(col, choice, start):
... for key in d[col]:
... if key.startswith(choice, start):#I use startswith because my real keys are longer
... d[col].update({key:0}) # or d[col][key]=0
...
>>> populate(1, 'g', 2)
>>> print d
{0: {'lfm': 1, 'lfg': 1, 'lwg': 1, 'lwm': 1}, 1: {'lfm': 1, 'lfg': 0, 'lwg': 0, 'lwm': 1}}
I suspect I know what's going on thoughOutput:>>> inner = {'lfm':1, 'lfg':1, 'lwg': 1, 'lwm': 1}
>>> d = {0: inner, 1: inner}
>>> populate(1, 'g', 2)
>>> d
{0: {'lfm': 1, 'lfg': 0, 'lwg': 0, 'lwm': 1}, 1: {'lfm': 1, 'lfg': 0, 'lwg': 0, 'lwm': 1}}
In this second bit of code, I'm creating a single "inner" dictionary and re-using it. Note that in this case, the dictionary isn't copied, it's just reused. So when it gets mutated, that mutation is visible in two places. When you're constructing your outer dictionary, you probably want to copy the dictionary before inserting it.