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: Change key name in a list of dictionaries

What is a pythonic way to remap each dictionary key in a list of dictionaries to different key names? The new name must be a concatenation between the existing key and the value of a list (value of list+"-"+ key), for the same index. E.g,

List of dictionaries:

[[{'Capture & Acquis.': '','Storage & Accounting': 'X','Transformation': ''}],
 [{'Process': 'Acquisition','Report': 'Final'}],
 [{'Responsible': 'APE','Department': 'ACC'}]]

List of Names to add:

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

['Dataflow','Scope','Owner']

Final output

[[{'Dataflow-Capture': '','Dataflow-Storage': 'X','Dataflow-Transformation': ''}],
 [{'Scope-Process': 'Acquisition','Scope-Report': 'Final'}],
 [{'Owner-Responsible': 'APE','Owner-Department': 'ACC'}]]

>Solution :

Try:

lst_a = [
    [
        {
            "Capture & Acquis.": "",
            "Storage & Accounting": "X",
            "Transformation": "",
        }
    ],
    [{"Process": "Acquisition", "Report": "Final"}],
    [{"Responsible": "APE", "Department": "ACC"}],
]

lst_b = ["Dataflow", "Scope", "Owner"]

for l, prefix in zip(lst_a, lst_b):
    l[0] = {f"{prefix}-{k.split()[0]}": v for k, v in l[0].items()}

print(lst_a)

Prints:

[
    [
        {
            "Dataflow-Capture": "",
            "Dataflow-Storage": "X",
            "Dataflow-Transformation": "",
        }
    ],
    [{"Scope-Process": "Acquisition", "Scope-Report": "Final"}],
    [{"Owner-Responsible": "APE", "Owner-Department": "ACC"}],
]
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