Search code examples
pythonlogic

unexpected output in python change in my variable


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'}}

Solution

  • 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'}}