0

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'}}
matszwecja
  • 6,357
  • 2
  • 10
  • 17

1 Answers1

0

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'}}
funnydman
  • 9,083
  • 4
  • 40
  • 55
  • Thankyou sir. Sir I have another ans, but unable to differentiate between your and and mine. I am still a bigginer. using dict keyword instead of deepcopy – Sachin Sangwan Aug 08 '22 at 12:25
  • See this https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy – funnydman Aug 08 '22 at 12:35