unexpected output in python change in my variable

Question:

I want to print a dict – if name in ans[‘stderr’] then output dict containing complete = False else stderr to be


    data = []
    names = ["abc", "xyz"]
    ans = {
            'complete': True, 
            'stdout': '', 
            'stderr': "if XYZ complete must be False else stderr should be null", 
           }
    
    for alpha in names:
        tmp_dict = {}
        tmp_dict['path'] = alpha
        tmp_dict['retval'] = ans
        
        if alpha.lower() in ans['stderr'].lower():
            print("CONDITION MATCHED")
            tmp_dict['retval']['complete'] = False
        else:
            print('NOT MATCHED')
            tmp_dict['retval']['stderr'] = ""
        print(tmp_dict)

Expected output:  

{'path': 'abc', 'retval': {'complete': True, 'stdout': '', 'stderr': ''}}
CONDITION MATCHED
{'path': 'xyz', 'retval': {'complete': False, 'stdout': '', 'stderr': 'if XYZ complete must be False else stderr should be null'}}
Asked By: Sachin Sangwan

||

Answers:

You need to copy your dict, before assigning it to tmp_dict:

from copy import deepcopy

data = []
names = ["abc", "xyz"]
ans = {
    'complete': True,
    'stdout': '',
    'stderr': "if XYZ complete must be False else stderr should be null",
}

for alpha in names:
    tmp_dict = {}
    tmp_dict['path'] = alpha
    tmp_dict['retval'] = deepcopy(ans)

    if alpha.lower() in ans['stderr'].lower():
        print("CONDITION MATCHED")
        tmp_dict['retval']['complete'] = False
    else:
        print('NOT MATCHED')
        tmp_dict['retval']['stderr'] = ""
    print(tmp_dict)

Ouptut:

NOT MATCHED
{'path': 'abc', 'retval': {'complete': True, 'stdout': '', 'stderr': ''}}
CONDITION MATCHED
{'path': 'xyz', 'retval': {'complete': False, 'stdout': '', 'stderr': 'if XYZ complete must be False else stderr should be null'}}
Answered By: funnydman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.