Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python / double for-loop iteration over dictionary and json file not working properly

i wrote an little algorithm that iterates over a dictionary and then over a json file with the goal to replace specific keys.

I have three items in the dictionary that should be replaced. The problem is that the function only replaces the first entry from the dictionary and not the other ones but the foor loop is iterated three times, like it should.

I think its a logical error but i dont find it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Replacer:
    def __init__(self, form_json_path: str, replace_dict: dict):
        self.file_read = open (f'{form_json_path}', 'r')
        self.file_path = form_json_path
        self.replace_dict = replace_dict

    def replace_keys(self):
        replaced_json = ''

        for before, after in self.replace_dict.items():
            search_phrase = f'"key":"{before}"'
            additional_search_phrase = f'"key": "{before}"'

            for line in self.file_read:
                if (search_phrase in line or additional_search_phrase in line):
                    replaced_json_line = line.replace(f'{before}', f'{after}')
                    replaced_json += replaced_json_line
                else:
                    replaced_json += line

        print(replaced_json)
        self.file_read.close()


keys_to_replace = {
    "antragsumfang_Panel": "antragsumfang_PanelREPLACED",
    "antragsumfangHinweis_HTMLElement": "antragsumfangHinweis_HTMLElementREPLACED",
    "antragsumfangHinweisZwei_HTMLElement": "antragsumfangHinweisZwei_HTMLElementREPLACED"
}

f = Replacer('t.json', keys_to_replace)
f.replace_keys()

>Solution :

The issue lies in the inner loop. Files objects do not automatically go back to the beginning of the file when they reach the end. The first time, it iterates over the lines as it should but the second and third times it does nothing because it is already at the end.
To fix this add self.file_read.seek(0) after the inner loop to go back to the beginning of the file.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading