Search code examples
pythondictionary

Transform a list of dictionaries, based on key list


In Python 3.9, I have a list of dictionaries:

variables = [
    {'id': ['alpha'], 'ip': '10.10.10.10', 'name': 'primary'},
    {'id': ['beta', 'gamma'], 'ip': '10.10.10.20', 'name': 'secondary'}
]

My goal is to transform it into this dictionary format:

result = {
    'alpha.ip': '10.10.10.10',
    'alpha.name': 'primary',
    'beta.ip': '10.10.10.20',
    'beta.name': 'secondary',
    'gamma.ip': '10.10.10.20',
    'gamma.name': 'secondary'
}

I have a difficult time drafting the id loop logic, which will produce the correct result.


Solution

  • You need to iterate through the variables list and, for each entry, loop through its id list. For each id, you will then generate two key-value pairs: one for the IP and one for the name.

    variables = [
        {'id': ['alpha'], 'ip': '10.10.10.10', 'name': 'primary'},
        {'id': ['beta', 'gamma'], 'ip': '10.10.10.20', 'name': 'secondary'}
    ]
    
    result = {}
    
    for var in variables:
        for id_value in var['id']:
            result[f"{id_value}.ip"] = var['ip']
            result[f"{id_value}.name"] = var['name']
    
    print(result)
    

    which derives:

    {
        'alpha.ip': '10.10.10.10',
        'alpha.name': 'primary',
        'beta.ip': '10.10.10.20',
        'beta.name': 'secondary',
        'gamma.ip': '10.10.10.20',
        'gamma.name': 'secondary'
    }