Python: Change key name in a list of dictionaries

Question:

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:

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

Final output

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

||

Answers:

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"}],
]
Answered By: Andrej Kesely
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.