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

Pass dictionary keys into function

I want to write a function that accesses a dictionary key and renames it if the key exists. For example:

def json_rename(json_input, json_output, to_replace):
    json_output = []
    
    for j in json_input:
        try:
            j["key1"][0]["key_2"] = j["key1"][0].pop(to_replace)
            json.output.append(j)
        except:
            json.output.append(j)
   
    return json_output

j["key1"][0]["key_2"] could be any combination of keys, but how do I pass those as arguments?

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

>Solution :

I would pass in a list that represents the "path" of your target key. For example:

import contextlib

def rename_key(json_input, path, new_key):
    for j in json_input:
        with contextlib.suppress(KeyError):
            for p in path[:-1]:
                j = j[p]
            j[new_key] = j[path[-1]]
            del j[path[-1]]

rename_key(json_input, ['key1', 0, 'key2'], 'New Key 2')
rename_key(json_input, ['key3', 'key4', 1, 'key5'], 'New Key 5')
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