Apr-25-2018, 06:16 PM
I am having a problem with over-accessing and changing values in a dictionary within a dictionary using the method 'startswith'.
I have a basic dictionary (the dictionary for which I want this to work is larger, hence the need for functions to do the work for me) for the trial:
So why is d[col] not selecting only one dictionary.
Really frustrated.
John
I have a basic dictionary (the dictionary for which I want this to work is larger, hence the need for functions to do the work for me) for the trial:
d = {0:{'lfm':1, 'lfg':1, 'lwg': 1, 'lwm': 1},1:{'lfm': 1, 'lfg': 1, 'lwg': 1, 'lwm': 1}}Now I want to change some values in only one of the interior dictionaries, so I define a function:
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]=0and use
populate(1, 'g', 2)This should change any value that ends in 'g' within the second inner dictionary, but not the first; yet it changes values that end in 'g' in the first inner dictionary, as can be seen:
d={0: {'lfm':1, 'lfg':0, 'lwg':0, 'lwm':1}, 1: {'lfm':1, 'lfg':0, 'lwg': 0, 'lwm': 1}}I have done an intermediate print as the last line in the 'populate' function, within the 'if' statement, and it shows that it is picking up the right values but also changing the wrong values.
So why is d[col] not selecting only one dictionary.
Really frustrated.
John